diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml
index 029fdf1d32..1ffe48119a 100644
--- a/.github/workflows/maven.yml
+++ b/.github/workflows/maven.yml
@@ -1,7 +1,7 @@
# This workflow is designed to build PRs for AHC. Note that it does not actually publish AHC, just builds and test it.
# Docs: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
-name: Build and Test PR
+name: Build PR
on:
push:
@@ -17,9 +17,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
+ - name: Grant Permission
+ run: sudo chmod +x ./mvnw
- uses: actions/setup-java@v3
with:
distribution: 'corretto'
java-version: '11'
- name: Run Tests
- run: mvn -B -ntp clean test
+ run: ./mvnw -B -ntp clean test
diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar
new file mode 100644
index 0000000000..bf82ff01c6
Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ
diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 0000000000..df0cd8a0f2
--- /dev/null
+++ b/.mvn/wrapper/maven-wrapper.properties
@@ -0,0 +1,18 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+distributionUrl=https://maven-central.storage-download.googleapis.com/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
+wrapperUrl=https://maven-central.storage-download.googleapis.com/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 0db607f4da..0000000000
--- a/.travis.yml
+++ /dev/null
@@ -1,22 +0,0 @@
-language: java
-jdk:
- - openjdk8
-
-before_script:
- - travis/before_script.sh
-
-script:
- - mvn test javadoc:javadoc -Ptest-output
- - find $HOME/.m2 -name "_remote.repositories" | xargs rm
- - find $HOME/.m2 -name "resolver-status.properties" | xargs rm -f
-
-# If building master, Publish to Sonatype
-after_success:
- - travis/after_success.sh
-
-sudo: false
-
-# Cache settings
-cache:
- directories:
- - $HOME/.m2/repository
diff --git a/bom/pom.xml b/bom/pom.xml
deleted file mode 100644
index 021a5f2e0b..0000000000
--- a/bom/pom.xml
+++ /dev/null
@@ -1,108 +0,0 @@
-
-
- 4.0.0
-
-
- org.asynchttpclient
- async-http-client-project
- 2.12.4-SNAPSHOT
-
-
- async-http-client-bom
- pom
- Asynchronous Http Client Bill of Materials (BOM)
- Importing this BOM will provide dependency management for all AsyncHttpClient artifacts.
- http://github.com/AsyncHttpClient/async-http-client/bom
-
-
-
-
- org.asynchttpclient
- async-http-client
- ${project.version}
-
-
- org.asynchttpclient
- async-http-client-example
- ${project.version}
-
-
- org.asynchttpclient
- async-http-client-extras-guava
- ${project.version}
-
-
- org.asynchttpclient
- async-http-client-extras-jdeferred
- ${project.version}
-
-
- org.asynchttpclient
- async-http-client-extras-registry
- ${project.version}
-
-
- org.asynchttpclient
- async-http-client-extras-retrofit2
- ${project.version}
-
-
- org.asynchttpclient
- async-http-client-extras-rxjava
- ${project.version}
-
-
- org.asynchttpclient
- async-http-client-extras-rxjava2
- ${project.version}
-
-
- org.asynchttpclient
- async-http-client-extras-simple
- ${project.version}
-
-
- org.asynchttpclient
- async-http-client-extras-typesafe-config
- ${project.version}
-
-
- org.asynchttpclient
- async-http-client-netty-utils
- ${project.version}
-
-
-
-
-
-
-
-
- org.codehaus.mojo
- flatten-maven-plugin
- 1.1.0
- false
-
-
- flatten
- process-resources
-
- flatten
-
-
- bom
-
- remove
- remove
- remove
-
-
-
-
-
-
-
-
diff --git a/client/pom.xml b/client/pom.xml
index 105219ccc6..cfa0a08e2d 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -3,85 +3,32 @@
org.asynchttpclient
async-http-client-project
- 2.12.4-SNAPSHOT
+ 3.0.0-SNAPSHOT
+
4.0.0
async-http-client
- Asynchronous Http Client
+ AHC/Client
The Async Http Client (AHC) classes.
org.asynchttpclient.client
-
-
-
- maven-jar-plugin
-
-
-
- test-jar
-
-
-
-
-
-
-
+
- org.asynchttpclient
- async-http-client-netty-utils
- ${project.version}
-
-
- io.netty
- netty-codec-http
-
-
- io.netty
- netty-handler
-
-
- io.netty
- netty-codec-socks
-
-
- io.netty
- netty-handler-proxy
-
-
- io.netty
- netty-transport-native-epoll
- linux-x86_64
-
-
- io.netty
- netty-transport-native-kqueue
- osx-x86_64
-
-
- org.reactivestreams
- reactive-streams
-
-
- com.typesafe.netty
- netty-reactive-streams
-
-
- io.reactivex.rxjava2
- rxjava
- test
-
-
- org.reactivestreams
- reactive-streams-examples
+ commons-fileupload
+ commons-fileupload
+ 1.4
test
+
+
- org.apache.kerby
- kerb-simplekdc
+ javax.portlet
+ portlet-api
+ 3.0.1
test
diff --git a/client/src/main/java/org/asynchttpclient/AsyncCompletionHandler.java b/client/src/main/java/org/asynchttpclient/AsyncCompletionHandler.java
index 842aa5dae5..fe193d37f9 100644
--- a/client/src/main/java/org/asynchttpclient/AsyncCompletionHandler.java
+++ b/client/src/main/java/org/asynchttpclient/AsyncCompletionHandler.java
@@ -21,15 +21,19 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.io.File;
+import java.io.InputStream;
+import java.util.concurrent.Future;
+
/**
* An {@link AsyncHandler} augmented with an {@link #onCompleted(Response)}
* convenience method which gets called when the {@link Response} processing is
* finished. This class also implements the {@link ProgressAsyncHandler}
* callback, all doing nothing except returning
- * {@link org.asynchttpclient.AsyncHandler.State#CONTINUE}
+ * {@link AsyncHandler.State#CONTINUE}
*
* @param Type of the value that will be returned by the associated
- * {@link java.util.concurrent.Future}
+ * {@link Future}
*/
public abstract class AsyncCompletionHandler implements ProgressAsyncHandler {
@@ -76,15 +80,15 @@ public void onThrowable(Throwable t) {
*
* @param response The {@link Response}
* @return T Value that will be returned by the associated
- * {@link java.util.concurrent.Future}
+ * {@link Future}
* @throws Exception if something wrong happens
*/
- abstract public T onCompleted(Response response) throws Exception;
+ public abstract T onCompleted(Response response) throws Exception;
/**
* Invoked when the HTTP headers have been fully written on the I/O socket.
*
- * @return a {@link org.asynchttpclient.AsyncHandler.State} telling to CONTINUE
+ * @return a {@link AsyncHandler.State} telling to CONTINUE
* or ABORT the current processing.
*/
@Override
@@ -93,10 +97,10 @@ public State onHeadersWritten() {
}
/**
- * Invoked when the content (a {@link java.io.File}, {@link String} or
- * {@link java.io.InputStream} has been fully written on the I/O socket.
+ * Invoked when the content (a {@link File}, {@link String} or
+ * {@link InputStream} has been fully written on the I/O socket.
*
- * @return a {@link org.asynchttpclient.AsyncHandler.State} telling to CONTINUE
+ * @return a {@link AsyncHandler.State} telling to CONTINUE
* or ABORT the current processing.
*/
@Override
@@ -111,7 +115,7 @@ public State onContentWritten() {
* @param amount The amount of bytes to transfer
* @param current The amount of bytes transferred
* @param total The total number of bytes transferred
- * @return a {@link org.asynchttpclient.AsyncHandler.State} telling to CONTINUE
+ * @return a {@link AsyncHandler.State} telling to CONTINUE
* or ABORT the current processing.
*/
@Override
diff --git a/client/src/main/java/org/asynchttpclient/AsyncCompletionHandlerBase.java b/client/src/main/java/org/asynchttpclient/AsyncCompletionHandlerBase.java
index 15301c2bb0..3498bd6439 100644
--- a/client/src/main/java/org/asynchttpclient/AsyncCompletionHandlerBase.java
+++ b/client/src/main/java/org/asynchttpclient/AsyncCompletionHandlerBase.java
@@ -21,9 +21,6 @@
* Simple {@link AsyncHandler} of type {@link Response}
*/
public class AsyncCompletionHandlerBase extends AsyncCompletionHandler {
- /**
- * {@inheritDoc}
- */
@Override
public Response onCompleted(Response response) throws Exception {
return response;
diff --git a/client/src/main/java/org/asynchttpclient/AsyncHandler.java b/client/src/main/java/org/asynchttpclient/AsyncHandler.java
index 44c203099d..80a1fc1915 100644
--- a/client/src/main/java/org/asynchttpclient/AsyncHandler.java
+++ b/client/src/main/java/org/asynchttpclient/AsyncHandler.java
@@ -22,6 +22,7 @@
import javax.net.ssl.SSLSession;
import java.net.InetSocketAddress;
import java.util.List;
+import java.util.concurrent.Future;
/**
@@ -55,7 +56,7 @@
* There's a chance you might end up in a dead lock.
* If you really need to perform a blocking operation, execute it in a different dedicated thread pool.
*
- * @param Type of object returned by the {@link java.util.concurrent.Future#get}
+ * @param Type of object returned by the {@link Future#get}
*/
public interface AsyncHandler {
@@ -111,7 +112,7 @@ default State onTrailingHeadersReceived(HttpHeaders headers) throws Exception {
*
* Gets always invoked as last callback method.
*
- * @return T Value that will be returned by the associated {@link java.util.concurrent.Future}
+ * @return T Value that will be returned by the associated {@link Future}
* @throws Exception if something wrong happens
*/
T onCompleted() throws Exception;
diff --git a/client/src/main/java/org/asynchttpclient/AsyncHttpClient.java b/client/src/main/java/org/asynchttpclient/AsyncHttpClient.java
index d42918861a..a08352647b 100755
--- a/client/src/main/java/org/asynchttpclient/AsyncHttpClient.java
+++ b/client/src/main/java/org/asynchttpclient/AsyncHttpClient.java
@@ -248,7 +248,7 @@ public interface AsyncHttpClient extends Closeable {
*
* @param request {@link Request}
* @param handler an instance of {@link AsyncHandler}
- * @param Type of the value that will be returned by the associated {@link java.util.concurrent.Future}
+ * @param Type of the value that will be returned by the associated {@link Future}
* @return a {@link Future} of type T
*/
ListenableFuture executeRequest(Request request, AsyncHandler handler);
@@ -258,7 +258,7 @@ public interface AsyncHttpClient extends Closeable {
*
* @param requestBuilder {@link RequestBuilder}
* @param handler an instance of {@link AsyncHandler}
- * @param Type of the value that will be returned by the associated {@link java.util.concurrent.Future}
+ * @param Type of the value that will be returned by the associated {@link Future}
* @return a {@link Future} of type T
*/
ListenableFuture executeRequest(RequestBuilder requestBuilder, AsyncHandler handler);
diff --git a/client/src/main/java/org/asynchttpclient/AsyncHttpClientConfig.java b/client/src/main/java/org/asynchttpclient/AsyncHttpClientConfig.java
index a4cf8cb46b..1fbe1b35b4 100644
--- a/client/src/main/java/org/asynchttpclient/AsyncHttpClientConfig.java
+++ b/client/src/main/java/org/asynchttpclient/AsyncHttpClientConfig.java
@@ -19,6 +19,7 @@
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.handler.ssl.SslContext;
+import io.netty.util.HashedWheelTimer;
import io.netty.util.Timer;
import org.asynchttpclient.channel.ChannelPool;
import org.asynchttpclient.channel.KeepAliveStrategy;
@@ -32,6 +33,7 @@
import org.asynchttpclient.proxy.ProxyServer;
import org.asynchttpclient.proxy.ProxyServerSelector;
+import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadFactory;
@@ -142,10 +144,10 @@ public interface AsyncHttpClientConfig {
boolean isCompressionEnforced();
/**
- * Return the {@link java.util.concurrent.ThreadFactory} an {@link AsyncHttpClient} use for handling asynchronous response.
+ * Return the {@link ThreadFactory} an {@link AsyncHttpClient} use for handling asynchronous response.
*
- * @return the {@link java.util.concurrent.ThreadFactory} an {@link AsyncHttpClient} use for handling asynchronous response. If no {@link ThreadFactory} has been explicitly
- * provided, this method will return null
+ * @return the {@link ThreadFactory} an {@link AsyncHttpClient} use for handling asynchronous response. If no {@link ThreadFactory} has been explicitly
+ * provided, this method will return {@code null}
*/
ThreadFactory getThreadFactory();
@@ -185,9 +187,9 @@ public interface AsyncHttpClientConfig {
List getResponseFilters();
/**
- * Return the list of {@link java.io.IOException}
+ * Return the list of {@link IOException}
*
- * @return Unmodifiable list of {@link java.io.IOException}
+ * @return Unmodifiable list of {@link IOException}
*/
List getIoExceptionFilters();
@@ -206,9 +208,9 @@ public interface AsyncHttpClientConfig {
int expiredCookieEvictionDelay();
/**
- * Return the number of time the library will retry when an {@link java.io.IOException} is throw by the remote server
+ * Return the number of time the library will retry when an {@link IOException} is throw by the remote server
*
- * @return the number of time the library will retry when an {@link java.io.IOException} is throw by the remote server
+ * @return the number of time the library will retry when an {@link IOException} is throw by the remote server
*/
int getMaxRequestRetry();
@@ -226,7 +228,7 @@ public interface AsyncHttpClientConfig {
* In the case of a POST/Redirect/Get scenario where the server uses a 302 for the redirect, should AHC respond to the redirect with a GET or whatever the original method was.
* Unless configured otherwise, for a 302, AHC, will use a GET for this case.
*
- * @return true if strict 302 handling is to be used, otherwise false.
+ * @return true if strict 302 handling is to be used, otherwise {@code false}.
*/
boolean isStrict302Handling();
@@ -314,12 +316,12 @@ public interface AsyncHttpClientConfig {
Timer getNettyTimer();
/**
- * @return the duration between tick of {@link io.netty.util.HashedWheelTimer}
+ * @return the duration between tick of {@link HashedWheelTimer}
*/
long getHashedWheelTimerTickDuration();
/**
- * @return the size of the hashed wheel {@link io.netty.util.HashedWheelTimer}
+ * @return the size of the hashed wheel {@link HashedWheelTimer}
*/
int getHashedWheelTimerSize();
diff --git a/client/src/main/java/org/asynchttpclient/ClientStats.java b/client/src/main/java/org/asynchttpclient/ClientStats.java
index d6e4efa4a4..e12a4bfd25 100644
--- a/client/src/main/java/org/asynchttpclient/ClientStats.java
+++ b/client/src/main/java/org/asynchttpclient/ClientStats.java
@@ -79,8 +79,12 @@ public String toString() {
@Override
public boolean equals(final Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
final ClientStats that = (ClientStats) o;
return Objects.equals(statsPerHost, that.statsPerHost);
}
diff --git a/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClient.java b/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClient.java
index 49a596c435..59bcd61b27 100644
--- a/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClient.java
+++ b/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClient.java
@@ -85,7 +85,7 @@ public DefaultAsyncHttpClient() {
public DefaultAsyncHttpClient(AsyncHttpClientConfig config) {
this.config = config;
- this.noRequestFilters = config.getRequestFilters().isEmpty();
+ noRequestFilters = config.getRequestFilters().isEmpty();
allowStopNettyTimer = config.getNettyTimer() == null;
nettyTimer = allowStopNettyTimer ? newNettyTimer(config) : config.getNettyTimer();
@@ -106,7 +106,7 @@ public DefaultAsyncHttpClient(AsyncHttpClientConfig config) {
}
}
- private Timer newNettyTimer(AsyncHttpClientConfig config) {
+ private static Timer newNettyTimer(AsyncHttpClientConfig config) {
ThreadFactory threadFactory = config.getThreadFactory() != null ? config.getThreadFactory() : new DefaultThreadFactory(config.getThreadPoolName() + "-timer");
HashedWheelTimer timer = new HashedWheelTimer(threadFactory, config.getHashedWheelTimerTickDuration(), TimeUnit.MILLISECONDS, config.getHashedWheelTimerSize());
timer.start();
@@ -278,12 +278,12 @@ private FilterContext preProcessRequest(FilterContext fc) throws Filte
Request request = fc.getRequest();
if (fc.getAsyncHandler() instanceof ResumableAsyncHandler) {
- request = ResumableAsyncHandler.class.cast(fc.getAsyncHandler()).adjustRequestRange(request);
+ request = ((ResumableAsyncHandler) fc.getAsyncHandler()).adjustRequestRange(request);
}
if (request.getRangeOffset() != 0) {
RequestBuilder builder = request.toBuilder();
- builder.setHeader("Range", "bytes=" + request.getRangeOffset() + "-");
+ builder.setHeader("Range", "bytes=" + request.getRangeOffset() + '-');
request = builder.build();
}
fc = new FilterContext.FilterContextBuilder<>(fc).request(request).build();
@@ -318,6 +318,6 @@ protected BoundRequestBuilder requestBuilder(Request prototype) {
@Override
public AsyncHttpClientConfig getConfig() {
- return this.config;
+ return config;
}
}
diff --git a/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClientConfig.java b/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClientConfig.java
index 37bf8675e8..17d009dcca 100644
--- a/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClientConfig.java
+++ b/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClientConfig.java
@@ -833,7 +833,7 @@ public static class Builder {
private int chunkedFileChunkSize = defaultChunkedFileChunkSize();
private boolean useNativeTransport = defaultUseNativeTransport();
private ByteBufAllocator allocator;
- private Map, Object> channelOptions = new HashMap<>();
+ private final Map, Object> channelOptions = new HashMap<>();
private EventLoopGroup eventLoopGroup;
private Timer nettyTimer;
private ThreadFactory threadFactory;
@@ -961,7 +961,7 @@ public Builder setRealm(Realm realm) {
}
public Builder setRealm(Realm.Builder realmBuilder) {
- this.realm = realmBuilder.build();
+ realm = realmBuilder.build();
return this;
}
@@ -1001,7 +1001,7 @@ public Builder setValidateResponseHeaders(boolean validateResponseHeaders) {
}
public Builder setProxyServer(ProxyServer proxyServer) {
- this.proxyServerSelector = uri -> proxyServer;
+ proxyServerSelector = uri -> proxyServer;
return this;
}
@@ -1345,14 +1345,17 @@ public Builder setIoThreadsCount(int ioThreadsCount) {
}
private ProxyServerSelector resolveProxyServerSelector() {
- if (proxyServerSelector != null)
+ if (proxyServerSelector != null) {
return proxyServerSelector;
+ }
- if (useProxySelector)
+ if (useProxySelector) {
return ProxyUtils.getJdkDefaultProxyServerSelector();
+ }
- if (useProxyProperties)
+ if (useProxyProperties) {
return ProxyUtils.createProxyServerSelector(System.getProperties());
+ }
return ProxyServerSelector.NO_PROXY_SELECTOR;
}
diff --git a/client/src/main/java/org/asynchttpclient/DefaultRequest.java b/client/src/main/java/org/asynchttpclient/DefaultRequest.java
index 7115878545..8d83ec852b 100644
--- a/client/src/main/java/org/asynchttpclient/DefaultRequest.java
+++ b/client/src/main/java/org/asynchttpclient/DefaultRequest.java
@@ -61,6 +61,7 @@ public class DefaultRequest implements Request {
private final Charset charset;
private final ChannelPoolPartitioning channelPoolPartitioning;
private final NameResolver nameResolver;
+
// lazily loaded
private List queryParams;
@@ -248,47 +249,50 @@ public NameResolver getNameResolver() {
@Override
public List getQueryParams() {
- if (queryParams == null)
- // lazy load
+ // lazy load
+ if (queryParams == null) {
if (isNonEmpty(uri.getQuery())) {
queryParams = new ArrayList<>(1);
for (String queryStringParam : uri.getQuery().split("&")) {
int pos = queryStringParam.indexOf('=');
- if (pos <= 0)
+ if (pos <= 0) {
queryParams.add(new Param(queryStringParam, null));
- else
+ } else {
queryParams.add(new Param(queryStringParam.substring(0, pos), queryStringParam.substring(pos + 1)));
+ }
}
- } else
+ } else {
queryParams = Collections.emptyList();
+ }
+ }
return queryParams;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(getUrl());
-
- sb.append("\t");
+ sb.append('\t');
sb.append(method);
sb.append("\theaders:");
+
if (!headers.isEmpty()) {
for (Map.Entry header : headers) {
- sb.append("\t");
+ sb.append('\t');
sb.append(header.getKey());
- sb.append(":");
+ sb.append(':');
sb.append(header.getValue());
}
}
+
if (isNonEmpty(formParams)) {
sb.append("\tformParams:");
for (Param param : formParams) {
- sb.append("\t");
+ sb.append('\t');
sb.append(param.getName());
- sb.append(":");
+ sb.append(':');
sb.append(param.getValue());
}
}
-
return sb.toString();
}
}
diff --git a/client/src/main/java/org/asynchttpclient/Dsl.java b/client/src/main/java/org/asynchttpclient/Dsl.java
index a2063e72ec..d468e059c7 100644
--- a/client/src/main/java/org/asynchttpclient/Dsl.java
+++ b/client/src/main/java/org/asynchttpclient/Dsl.java
@@ -114,8 +114,7 @@ public static Realm.Builder realm(Realm prototype) {
}
public static Realm.Builder realm(AuthScheme scheme, String principal, String password) {
- return new Realm.Builder(principal, password)
- .setScheme(scheme);
+ return new Realm.Builder(principal, password).setScheme(scheme);
}
public static Realm.Builder basicAuthRealm(String principal, String password) {
diff --git a/client/src/main/java/org/asynchttpclient/HostStats.java b/client/src/main/java/org/asynchttpclient/HostStats.java
index 87d9278820..ccf75ce8ff 100644
--- a/client/src/main/java/org/asynchttpclient/HostStats.java
+++ b/client/src/main/java/org/asynchttpclient/HostStats.java
@@ -23,8 +23,7 @@ public class HostStats {
private final long activeConnectionCount;
private final long idleConnectionCount;
- public HostStats(long activeConnectionCount,
- long idleConnectionCount) {
+ public HostStats(long activeConnectionCount, long idleConnectionCount) {
this.activeConnectionCount = activeConnectionCount;
this.idleConnectionCount = idleConnectionCount;
}
@@ -60,11 +59,14 @@ public String toString() {
@Override
public boolean equals(final Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
final HostStats hostStats = (HostStats) o;
- return activeConnectionCount == hostStats.activeConnectionCount &&
- idleConnectionCount == hostStats.idleConnectionCount;
+ return activeConnectionCount == hostStats.activeConnectionCount && idleConnectionCount == hostStats.idleConnectionCount;
}
@Override
diff --git a/client/src/main/java/org/asynchttpclient/HttpResponseBodyPart.java b/client/src/main/java/org/asynchttpclient/HttpResponseBodyPart.java
index a420d3bdc7..0be4dedb51 100644
--- a/client/src/main/java/org/asynchttpclient/HttpResponseBodyPart.java
+++ b/client/src/main/java/org/asynchttpclient/HttpResponseBodyPart.java
@@ -24,7 +24,7 @@ public abstract class HttpResponseBodyPart {
private final boolean last;
- public HttpResponseBodyPart(boolean last) {
+ protected HttpResponseBodyPart(boolean last) {
this.last = last;
}
diff --git a/client/src/main/java/org/asynchttpclient/HttpResponseStatus.java b/client/src/main/java/org/asynchttpclient/HttpResponseStatus.java
index 4a349c15c7..60c82908ea 100644
--- a/client/src/main/java/org/asynchttpclient/HttpResponseStatus.java
+++ b/client/src/main/java/org/asynchttpclient/HttpResponseStatus.java
@@ -27,7 +27,7 @@ public abstract class HttpResponseStatus {
private final Uri uri;
- public HttpResponseStatus(Uri uri) {
+ protected HttpResponseStatus(Uri uri) {
this.uri = uri;
}
diff --git a/client/src/main/java/org/asynchttpclient/ListenableFuture.java b/client/src/main/java/org/asynchttpclient/ListenableFuture.java
index 1f5b965ec1..930d8d8c24 100755
--- a/client/src/main/java/org/asynchttpclient/ListenableFuture.java
+++ b/client/src/main/java/org/asynchttpclient/ListenableFuture.java
@@ -62,11 +62,11 @@ public interface ListenableFuture extends Future {
/**
* Adds a listener and executor to the ListenableFuture.
- * The listener will be {@linkplain java.util.concurrent.Executor#execute(Runnable) passed
+ * The listener will be {@linkplain Executor#execute(Runnable) passed
* to the executor} for execution when the {@code Future}'s computation is
* {@linkplain Future#isDone() complete}.
*
- * Executor can be null, in that case executor will be executed
+ * Executor can be {@code null}, in that case executor will be executed
* in the thread where completion happens.
*
* There is no guaranteed ordering of execution of listeners, they may get
diff --git a/client/src/main/java/org/asynchttpclient/Param.java b/client/src/main/java/org/asynchttpclient/Param.java
index d27e58e5fc..bd246984aa 100644
--- a/client/src/main/java/org/asynchttpclient/Param.java
+++ b/client/src/main/java/org/asynchttpclient/Param.java
@@ -32,14 +32,16 @@ public Param(String name, String value) {
}
public static List map2ParamList(Map> map) {
- if (map == null)
+ if (map == null) {
return null;
+ }
List params = new ArrayList<>(map.size());
for (Map.Entry> entries : map.entrySet()) {
String name = entries.getKey();
- for (String value : entries.getValue())
+ for (String value : entries.getValue()) {
params.add(new Param(name, value));
+ }
}
return params;
}
@@ -52,32 +54,38 @@ public String getValue() {
return value;
}
+ @Override
public int hashCode() {
final int prime = 31;
int result = 1;
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result + ((value == null) ? 0 : value.hashCode());
+ result = prime * result + (name == null ? 0 : name.hashCode());
+ result = prime * result + (value == null ? 0 : value.hashCode());
return result;
}
+ @Override
public boolean equals(Object obj) {
- if (this == obj)
+ if (this == obj) {
return true;
- if (obj == null)
+ }
+ if (obj == null) {
return false;
- if (!(obj instanceof Param))
+ }
+ if (!(obj instanceof Param)) {
return false;
+ }
Param other = (Param) obj;
if (name == null) {
- if (other.name != null)
+ if (other.name != null) {
return false;
- } else if (!name.equals(other.name))
+ }
+ } else if (!name.equals(other.name)) {
return false;
+ }
if (value == null) {
- if (other.value != null)
- return false;
- } else if (!value.equals(other.value))
- return false;
- return true;
+ return other.value == null;
+ } else {
+ return value.equals(other.value);
+ }
}
}
diff --git a/client/src/main/java/org/asynchttpclient/Realm.java b/client/src/main/java/org/asynchttpclient/Realm.java
index 535bd88a3d..6e4cbc8d29 100644
--- a/client/src/main/java/org/asynchttpclient/Realm.java
+++ b/client/src/main/java/org/asynchttpclient/Realm.java
@@ -271,7 +271,7 @@ public static class Builder {
private String ntlmDomain = System.getProperty("http.auth.ntlm.domain");
private Charset charset = UTF_8;
private String ntlmHost = "localhost";
- private boolean useAbsoluteURI = false;
+ private boolean useAbsoluteURI;
private boolean omitQuery;
/**
* Kerberos/Spnego properties
@@ -282,8 +282,8 @@ public static class Builder {
private String loginContextName;
public Builder() {
- this.principal = null;
- this.password = null;
+ principal = null;
+ password = null;
}
public Builder(String principal, String password) {
@@ -297,7 +297,7 @@ public Builder setNtlmDomain(String ntlmDomain) {
}
public Builder setNtlmHost(String host) {
- this.ntlmHost = host;
+ ntlmHost = host;
return this;
}
@@ -354,7 +354,7 @@ public Builder setMethodName(String methodName) {
}
public Builder setUsePreemptiveAuth(boolean usePreemptiveAuth) {
- this.usePreemptive = usePreemptiveAuth;
+ usePreemptive = usePreemptiveAuth;
return this;
}
@@ -393,7 +393,7 @@ public Builder setLoginContextName(String loginContextName) {
return this;
}
- private String parseRawQop(String rawQop) {
+ private static String parseRawQop(String rawQop) {
String[] rawServerSupportedQops = rawQop.split(",");
String[] serverSupportedQops = new String[rawServerSupportedQops.length];
for (int i = 0; i < rawServerSupportedQops.length; i++) {
@@ -402,13 +402,15 @@ private String parseRawQop(String rawQop) {
// prefer auth over auth-int
for (String rawServerSupportedQop : serverSupportedQops) {
- if (rawServerSupportedQop.equals("auth"))
+ if ("auth".equals(rawServerSupportedQop)) {
return rawServerSupportedQop;
+ }
}
for (String rawServerSupportedQop : serverSupportedQops) {
- if (rawServerSupportedQop.equals("auth-int"))
+ if ("auth-int".equals(rawServerSupportedQop)) {
return rawServerSupportedQop;
+ }
}
return null;
@@ -458,18 +460,19 @@ private void newCnonce(MessageDigest md) {
/**
* TODO: A Pattern/Matcher may be better.
*/
- private String match(String headerLine, String token) {
+ private static String match(String headerLine, String token) {
if (headerLine == null) {
return null;
}
int match = headerLine.indexOf(token);
- if (match <= 0)
+ if (match <= 0) {
return null;
+ }
// = to skip
match += token.length() + 1;
- int trailingComa = headerLine.indexOf(",", match);
+ int trailingComa = headerLine.indexOf(',', match);
String value = headerLine.substring(match, trailingComa > 0 ? trailingComa : headerLine.length());
value = value.length() > 0 && value.charAt(value.length() - 1) == '"'
? value.substring(0, value.length() - 1)
@@ -477,7 +480,7 @@ private String match(String headerLine, String token) {
return value.charAt(0) == '"' ? value.substring(1) : value;
}
- private byte[] md5FromRecycledStringBuilder(StringBuilder sb, MessageDigest md) {
+ private static byte[] md5FromRecycledStringBuilder(StringBuilder sb, MessageDigest md) {
md.update(StringUtils.charSequence2ByteBuffer(sb, ISO_8859_1));
sb.setLength(0);
return md.digest();
@@ -492,10 +495,11 @@ private byte[] ha1(StringBuilder sb, MessageDigest md) {
sb.append(principal).append(':').append(realmName).append(':').append(password);
byte[] core = md5FromRecycledStringBuilder(sb, md);
- if (algorithm == null || algorithm.equals("MD5")) {
+ if (algorithm == null || "MD5".equals(algorithm)) {
// A1 = username ":" realm-value ":" passwd
return core;
- } else if ("MD5-sess".equals(algorithm)) {
+ }
+ if ("MD5-sess".equals(algorithm)) {
// A1 = MD5(username ":" realm-value ":" passwd ) ":" nonce ":" cnonce
appendBase16(sb, core);
sb.append(':').append(nonce).append(':').append(cnonce);
@@ -516,7 +520,7 @@ private byte[] ha2(StringBuilder sb, String digestUri, MessageDigest md) {
// we would need a new API
sb.append(':').append(EMPTY_ENTITY_MD5);
- } else if (qop != null && !qop.equals("auth")) {
+ } else if (qop != null && !"auth".equals(qop)) {
throw new UnsupportedOperationException("Digest qop not supported: " + qop);
}
diff --git a/client/src/main/java/org/asynchttpclient/RequestBuilderBase.java b/client/src/main/java/org/asynchttpclient/RequestBuilderBase.java
index db455dbbf0..5294ccd4ac 100644
--- a/client/src/main/java/org/asynchttpclient/RequestBuilderBase.java
+++ b/client/src/main/java/org/asynchttpclient/RequestBuilderBase.java
@@ -57,7 +57,7 @@
*/
public abstract class RequestBuilderBase> {
- private final static Logger LOGGER = LoggerFactory.getLogger(RequestBuilderBase.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(RequestBuilderBase.class);
private static final Uri DEFAULT_REQUEST_URL = Uri.create("http://localhost");
public static NameResolver DEFAULT_NAME_RESOLVER = new DefaultNameResolver(ImmediateEventExecutor.INSTANCE);
// builder only fields
@@ -98,8 +98,8 @@ protected RequestBuilderBase(String method, boolean disableUrlEncoding) {
protected RequestBuilderBase(String method, boolean disableUrlEncoding, boolean validateHeaders) {
this.method = method;
- this.uriEncoder = UriEncoder.uriEncoder(disableUrlEncoding);
- this.headers = new DefaultHttpHeaders(validateHeaders);
+ uriEncoder = UriEncoder.uriEncoder(disableUrlEncoding);
+ headers = new DefaultHttpHeaders(validateHeaders);
}
protected RequestBuilderBase(Request prototype) {
@@ -107,39 +107,39 @@ protected RequestBuilderBase(Request prototype) {
}
protected RequestBuilderBase(Request prototype, boolean disableUrlEncoding, boolean validateHeaders) {
- this.method = prototype.getMethod();
- this.uriEncoder = UriEncoder.uriEncoder(disableUrlEncoding);
- this.uri = prototype.getUri();
- this.address = prototype.getAddress();
- this.localAddress = prototype.getLocalAddress();
- this.headers = new DefaultHttpHeaders(validateHeaders);
- this.headers.add(prototype.getHeaders());
+ method = prototype.getMethod();
+ uriEncoder = UriEncoder.uriEncoder(disableUrlEncoding);
+ uri = prototype.getUri();
+ address = prototype.getAddress();
+ localAddress = prototype.getLocalAddress();
+ headers = new DefaultHttpHeaders(validateHeaders);
+ headers.add(prototype.getHeaders());
if (isNonEmpty(prototype.getCookies())) {
- this.cookies = new ArrayList<>(prototype.getCookies());
+ cookies = new ArrayList<>(prototype.getCookies());
}
- this.byteData = prototype.getByteData();
- this.compositeByteData = prototype.getCompositeByteData();
- this.stringData = prototype.getStringData();
- this.byteBufferData = prototype.getByteBufferData();
- this.streamData = prototype.getStreamData();
- this.bodyGenerator = prototype.getBodyGenerator();
+ byteData = prototype.getByteData();
+ compositeByteData = prototype.getCompositeByteData();
+ stringData = prototype.getStringData();
+ byteBufferData = prototype.getByteBufferData();
+ streamData = prototype.getStreamData();
+ bodyGenerator = prototype.getBodyGenerator();
if (isNonEmpty(prototype.getFormParams())) {
- this.formParams = new ArrayList<>(prototype.getFormParams());
+ formParams = new ArrayList<>(prototype.getFormParams());
}
if (isNonEmpty(prototype.getBodyParts())) {
- this.bodyParts = new ArrayList<>(prototype.getBodyParts());
+ bodyParts = new ArrayList<>(prototype.getBodyParts());
}
- this.virtualHost = prototype.getVirtualHost();
- this.proxyServer = prototype.getProxyServer();
- this.realm = prototype.getRealm();
- this.file = prototype.getFile();
- this.followRedirect = prototype.getFollowRedirect();
- this.requestTimeout = prototype.getRequestTimeout();
- this.readTimeout = prototype.getReadTimeout();
- this.rangeOffset = prototype.getRangeOffset();
- this.charset = prototype.getCharset();
- this.channelPoolPartitioning = prototype.getChannelPoolPartitioning();
- this.nameResolver = prototype.getNameResolver();
+ virtualHost = prototype.getVirtualHost();
+ proxyServer = prototype.getProxyServer();
+ realm = prototype.getRealm();
+ file = prototype.getFile();
+ followRedirect = prototype.getFollowRedirect();
+ requestTimeout = prototype.getRequestTimeout();
+ readTimeout = prototype.getReadTimeout();
+ rangeOffset = prototype.getRangeOffset();
+ charset = prototype.getCharset();
+ channelPoolPartitioning = prototype.getChannelPoolPartitioning();
+ nameResolver = prototype.getNameResolver();
}
@SuppressWarnings("unchecked")
@@ -162,7 +162,7 @@ public T setAddress(InetAddress address) {
}
public T setLocalAddress(InetAddress address) {
- this.localAddress = address;
+ localAddress = address;
return asDerivedType();
}
@@ -177,7 +177,7 @@ public T setVirtualHost(String virtualHost) {
* @return {@code this}
*/
public T clearHeaders() {
- this.headers.clear();
+ headers.clear();
return asDerivedType();
}
@@ -199,7 +199,7 @@ public T setHeader(CharSequence name, String value) {
* @return {@code this}
*/
public T setHeader(CharSequence name, Object value) {
- this.headers.set(name, value);
+ headers.set(name, value);
return asDerivedType();
}
@@ -211,7 +211,7 @@ public T setHeader(CharSequence name, Object value) {
* @return {@code this}
*/
public T setHeader(CharSequence name, Iterable> values) {
- this.headers.set(name, values);
+ headers.set(name, values);
return asDerivedType();
}
@@ -239,7 +239,7 @@ public T addHeader(CharSequence name, Object value) {
value = "";
}
- this.headers.add(name, value);
+ headers.add(name, value);
return asDerivedType();
}
@@ -252,15 +252,16 @@ public T addHeader(CharSequence name, Object value) {
* @return {@code}
*/
public T addHeader(CharSequence name, Iterable> values) {
- this.headers.add(name, values);
+ headers.add(name, values);
return asDerivedType();
}
public T setHeaders(HttpHeaders headers) {
- if (headers == null)
+ if (headers == null) {
this.headers.clear();
- else
+ } else {
this.headers = headers;
+ }
return asDerivedType();
}
@@ -295,8 +296,9 @@ public T setSingleHeaders(Map extends CharSequence, ?> headers) {
}
private void lazyInitCookies() {
- if (this.cookies == null)
- this.cookies = new ArrayList<>(3);
+ if (cookies == null) {
+ cookies = new ArrayList<>(3);
+ }
}
public T setCookies(Collection cookies) {
@@ -306,7 +308,7 @@ public T setCookies(Collection cookies) {
public T addCookie(Cookie cookie) {
lazyInitCookies();
- this.cookies.add(cookie);
+ cookies.add(cookie);
return asDerivedType();
}
@@ -321,7 +323,7 @@ public T addOrReplaceCookie(Cookie cookie) {
boolean replace = false;
int index = 0;
lazyInitCookies();
- for (Cookie c : this.cookies) {
+ for (Cookie c : cookies) {
if (c.name().equals(cookieKey)) {
replace = true;
break;
@@ -329,39 +331,42 @@ public T addOrReplaceCookie(Cookie cookie) {
index++;
}
- if (replace)
- this.cookies.set(index, cookie);
- else
- this.cookies.add(cookie);
+ if (replace) {
+ cookies.set(index, cookie);
+ } else {
+ cookies.add(cookie);
+ }
return asDerivedType();
}
public void resetCookies() {
- if (this.cookies != null)
- this.cookies.clear();
+ if (cookies != null) {
+ cookies.clear();
+ }
}
public void resetQuery() {
queryParams = null;
- if (this.uri != null)
- this.uri = this.uri.withNewQuery(null);
+ if (uri != null) {
+ uri = uri.withNewQuery(null);
+ }
}
public void resetFormParams() {
- this.formParams = null;
+ formParams = null;
}
public void resetNonMultipartData() {
- this.byteData = null;
- this.compositeByteData = null;
- this.byteBufferData = null;
- this.stringData = null;
- this.streamData = null;
- this.bodyGenerator = null;
+ byteData = null;
+ compositeByteData = null;
+ byteBufferData = null;
+ stringData = null;
+ streamData = null;
+ bodyGenerator = null;
}
public void resetMultipartData() {
- this.bodyParts = null;
+ bodyParts = null;
}
public T setBody(File file) {
@@ -377,31 +382,31 @@ private void resetBody() {
public T setBody(byte[] data) {
resetBody();
- this.byteData = data;
+ byteData = data;
return asDerivedType();
}
public T setBody(List data) {
resetBody();
- this.compositeByteData = data;
+ compositeByteData = data;
return asDerivedType();
}
public T setBody(String data) {
resetBody();
- this.stringData = data;
+ stringData = data;
return asDerivedType();
}
public T setBody(ByteBuffer data) {
resetBody();
- this.byteBufferData = data;
+ byteBufferData = data;
return asDerivedType();
}
public T setBody(InputStream stream) {
resetBody();
- this.streamData = stream;
+ streamData = stream;
return asDerivedType();
}
@@ -419,17 +424,19 @@ public T setBody(BodyGenerator bodyGenerator) {
}
public T addQueryParam(String name, String value) {
- if (queryParams == null)
+ if (queryParams == null) {
queryParams = new ArrayList<>(1);
+ }
queryParams.add(new Param(name, value));
return asDerivedType();
}
public T addQueryParams(List params) {
- if (queryParams == null)
+ if (queryParams == null) {
queryParams = params;
- else
+ } else {
queryParams.addAll(params);
+ }
return asDerivedType();
}
@@ -439,8 +446,9 @@ public T setQueryParams(Map> map) {
public T setQueryParams(List params) {
// reset existing query
- if (this.uri != null && isNonEmpty(this.uri.getQuery()))
- this.uri = this.uri.withNewQuery(null);
+ if (uri != null && isNonEmpty(uri.getQuery())) {
+ uri = uri.withNewQuery(null);
+ }
queryParams = params;
return asDerivedType();
}
@@ -448,9 +456,10 @@ public T setQueryParams(List params) {
public T addFormParam(String name, String value) {
resetNonMultipartData();
resetMultipartData();
- if (this.formParams == null)
- this.formParams = new ArrayList<>(1);
- this.formParams.add(new Param(name, value));
+ if (formParams == null) {
+ formParams = new ArrayList<>(1);
+ }
+ formParams.add(new Param(name, value));
return asDerivedType();
}
@@ -461,16 +470,17 @@ public T setFormParams(Map> map) {
public T setFormParams(List params) {
resetNonMultipartData();
resetMultipartData();
- this.formParams = params;
+ formParams = params;
return asDerivedType();
}
public T addBodyPart(Part bodyPart) {
resetFormParams();
resetNonMultipartData();
- if (this.bodyParts == null)
- this.bodyParts = new ArrayList<>();
- this.bodyParts.add(bodyPart);
+ if (bodyParts == null) {
+ bodyParts = new ArrayList<>();
+ }
+ bodyParts.add(bodyPart);
return asDerivedType();
}
@@ -485,7 +495,7 @@ public T setProxyServer(ProxyServer proxyServer) {
}
public T setProxyServer(ProxyServer.Builder proxyServerBuilder) {
- this.proxyServer = proxyServerBuilder.build();
+ proxyServer = proxyServerBuilder.build();
return asDerivedType();
}
@@ -545,46 +555,51 @@ public T setSignatureCalculator(SignatureCalculator signatureCalculator) {
}
private RequestBuilderBase> executeSignatureCalculator() {
- if (signatureCalculator == null)
+ if (signatureCalculator == null) {
return this;
+ }
// build a first version of the request, without signatureCalculator in play
- RequestBuilder rb = new RequestBuilder(this.method);
+ RequestBuilder rb = new RequestBuilder(method);
// make copy of mutable collections so we don't risk affecting
// original RequestBuilder
// call setFormParams first as it resets other fields
- if (this.formParams != null)
- rb.setFormParams(this.formParams);
- if (this.headers != null)
- rb.headers.add(this.headers);
- if (this.cookies != null)
- rb.setCookies(this.cookies);
- if (this.bodyParts != null)
- rb.setBodyParts(this.bodyParts);
+ if (formParams != null) {
+ rb.setFormParams(formParams);
+ }
+ if (headers != null) {
+ rb.headers.add(headers);
+ }
+ if (cookies != null) {
+ rb.setCookies(cookies);
+ }
+ if (bodyParts != null) {
+ rb.setBodyParts(bodyParts);
+ }
// copy all other fields
// but rb.signatureCalculator, that's the whole point here
- rb.uriEncoder = this.uriEncoder;
- rb.queryParams = this.queryParams;
- rb.uri = this.uri;
- rb.address = this.address;
- rb.localAddress = this.localAddress;
- rb.byteData = this.byteData;
- rb.compositeByteData = this.compositeByteData;
- rb.stringData = this.stringData;
- rb.byteBufferData = this.byteBufferData;
- rb.streamData = this.streamData;
- rb.bodyGenerator = this.bodyGenerator;
- rb.virtualHost = this.virtualHost;
- rb.proxyServer = this.proxyServer;
- rb.realm = this.realm;
- rb.file = this.file;
- rb.followRedirect = this.followRedirect;
- rb.requestTimeout = this.requestTimeout;
- rb.rangeOffset = this.rangeOffset;
- rb.charset = this.charset;
- rb.channelPoolPartitioning = this.channelPoolPartitioning;
- rb.nameResolver = this.nameResolver;
+ rb.uriEncoder = uriEncoder;
+ rb.queryParams = queryParams;
+ rb.uri = uri;
+ rb.address = address;
+ rb.localAddress = localAddress;
+ rb.byteData = byteData;
+ rb.compositeByteData = compositeByteData;
+ rb.stringData = stringData;
+ rb.byteBufferData = byteBufferData;
+ rb.streamData = streamData;
+ rb.bodyGenerator = bodyGenerator;
+ rb.virtualHost = virtualHost;
+ rb.proxyServer = proxyServer;
+ rb.realm = realm;
+ rb.file = file;
+ rb.followRedirect = followRedirect;
+ rb.requestTimeout = requestTimeout;
+ rb.rangeOffset = rangeOffset;
+ rb.charset = charset;
+ rb.channelPoolPartitioning = channelPoolPartitioning;
+ rb.nameResolver = nameResolver;
Request unsignedRequest = rb.build();
signatureCalculator.calculateAndAddSignature(unsignedRequest, rb);
return rb;
@@ -602,7 +617,7 @@ private void updateCharset() {
private Uri computeUri() {
- Uri tempUri = this.uri;
+ Uri tempUri = uri;
if (tempUri == null) {
LOGGER.debug("setUrl hasn't been invoked. Using {}", DEFAULT_REQUEST_URL);
tempUri = DEFAULT_REQUEST_URL;
diff --git a/client/src/main/java/org/asynchttpclient/Response.java b/client/src/main/java/org/asynchttpclient/Response.java
index 0f3870ef3a..78a257e9c9 100644
--- a/client/src/main/java/org/asynchttpclient/Response.java
+++ b/client/src/main/java/org/asynchttpclient/Response.java
@@ -124,6 +124,7 @@ public interface Response {
*
* @return the textual representation
*/
+ @Override
String toString();
/**
@@ -190,8 +191,9 @@ public void accumulate(HttpHeaders headers) {
* @param bodyPart a body part (possibly empty, but will be filtered out)
*/
public void accumulate(HttpResponseBodyPart bodyPart) {
- if (bodyPart.length() > 0)
+ if (bodyPart.length() > 0) {
bodyParts.add(bodyPart);
+ }
}
/**
diff --git a/client/src/main/java/org/asynchttpclient/SignatureCalculator.java b/client/src/main/java/org/asynchttpclient/SignatureCalculator.java
index 3d81a78d1f..0341b6b1fa 100644
--- a/client/src/main/java/org/asynchttpclient/SignatureCalculator.java
+++ b/client/src/main/java/org/asynchttpclient/SignatureCalculator.java
@@ -23,6 +23,7 @@
*
* @since 1.1
*/
+@FunctionalInterface
public interface SignatureCalculator {
/**
* Method called when {@link RequestBuilder#build} method is called.
@@ -36,6 +37,5 @@ public interface SignatureCalculator {
* @param request Request that is being built; needed to access content to
* be signed
*/
- void calculateAndAddSignature(Request request,
- RequestBuilderBase> requestBuilder);
+ void calculateAndAddSignature(Request request, RequestBuilderBase> requestBuilder);
}
diff --git a/client/src/main/java/org/asynchttpclient/SslEngineFactory.java b/client/src/main/java/org/asynchttpclient/SslEngineFactory.java
index 4cdc0dbff5..2fa208c76d 100644
--- a/client/src/main/java/org/asynchttpclient/SslEngineFactory.java
+++ b/client/src/main/java/org/asynchttpclient/SslEngineFactory.java
@@ -16,6 +16,7 @@
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
+@FunctionalInterface
public interface SslEngineFactory {
/**
@@ -46,5 +47,4 @@ default void init(AsyncHttpClientConfig config) throws SSLException {
default void destroy() {
// no op
}
-
}
diff --git a/client/src/main/java/org/asynchttpclient/channel/ChannelPoolPartitioning.java b/client/src/main/java/org/asynchttpclient/channel/ChannelPoolPartitioning.java
index afc6135b7a..534aa361a2 100644
--- a/client/src/main/java/org/asynchttpclient/channel/ChannelPoolPartitioning.java
+++ b/client/src/main/java/org/asynchttpclient/channel/ChannelPoolPartitioning.java
@@ -16,6 +16,9 @@
import org.asynchttpclient.proxy.ProxyType;
import org.asynchttpclient.uri.Uri;
+import java.util.Objects;
+
+@FunctionalInterface
public interface ChannelPoolPartitioning {
Object getPartitionKey(Uri uri, String virtualHost, ProxyServer proxyServer);
@@ -24,6 +27,7 @@ enum PerHostChannelPoolPartitioning implements ChannelPoolPartitioning {
INSTANCE;
+ @Override
public Object getPartitionKey(Uri uri, String virtualHost, ProxyServer proxyServer) {
String targetHostBaseUrl = uri.getBaseUrl();
if (proxyServer == null) {
@@ -67,16 +71,27 @@ class CompositePartitionKey {
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
CompositePartitionKey that = (CompositePartitionKey) o;
- if (proxyPort != that.proxyPort) return false;
- if (targetHostBaseUrl != null ? !targetHostBaseUrl.equals(that.targetHostBaseUrl) : that.targetHostBaseUrl != null)
+ if (proxyPort != that.proxyPort) {
+ return false;
+ }
+ if (!Objects.equals(targetHostBaseUrl, that.targetHostBaseUrl)) {
+ return false;
+ }
+ if (!Objects.equals(virtualHost, that.virtualHost)) {
return false;
- if (virtualHost != null ? !virtualHost.equals(that.virtualHost) : that.virtualHost != null) return false;
- if (proxyHost != null ? !proxyHost.equals(that.proxyHost) : that.proxyHost != null) return false;
+ }
+ if (!Objects.equals(proxyHost, that.proxyHost)) {
+ return false;
+ }
return proxyType == that.proxyType;
}
diff --git a/client/src/main/java/org/asynchttpclient/channel/DefaultKeepAliveStrategy.java b/client/src/main/java/org/asynchttpclient/channel/DefaultKeepAliveStrategy.java
index 350927793b..d81a528ef1 100644
--- a/client/src/main/java/org/asynchttpclient/channel/DefaultKeepAliveStrategy.java
+++ b/client/src/main/java/org/asynchttpclient/channel/DefaultKeepAliveStrategy.java
@@ -19,9 +19,9 @@ public class DefaultKeepAliveStrategy implements KeepAliveStrategy {
*/
@Override
public boolean keepAlive(InetSocketAddress remoteAddress, Request ahcRequest, HttpRequest request, HttpResponse response) {
- return HttpUtil.isKeepAlive(response)
- && HttpUtil.isKeepAlive(request)
- // support non standard Proxy-Connection
- && !response.headers().contains("Proxy-Connection", CLOSE, true);
+ return HttpUtil.isKeepAlive(response) &&
+ HttpUtil.isKeepAlive(request) &&
+ // support non-standard Proxy-Connection
+ !response.headers().contains("Proxy-Connection", CLOSE, true);
}
}
diff --git a/client/src/main/java/org/asynchttpclient/channel/KeepAliveStrategy.java b/client/src/main/java/org/asynchttpclient/channel/KeepAliveStrategy.java
index 358fdf1e0c..d9cbe97c65 100644
--- a/client/src/main/java/org/asynchttpclient/channel/KeepAliveStrategy.java
+++ b/client/src/main/java/org/asynchttpclient/channel/KeepAliveStrategy.java
@@ -19,6 +19,7 @@
import java.net.InetSocketAddress;
+@FunctionalInterface
public interface KeepAliveStrategy {
/**
diff --git a/client/src/main/java/org/asynchttpclient/config/AsyncHttpClientConfigHelper.java b/client/src/main/java/org/asynchttpclient/config/AsyncHttpClientConfigHelper.java
index 1d038cb6c6..59f7aba41c 100644
--- a/client/src/main/java/org/asynchttpclient/config/AsyncHttpClientConfigHelper.java
+++ b/client/src/main/java/org/asynchttpclient/config/AsyncHttpClientConfigHelper.java
@@ -9,6 +9,9 @@ public class AsyncHttpClientConfigHelper {
private static volatile Config config;
+ private AsyncHttpClientConfigHelper() {
+ }
+
public static Config getAsyncHttpClientConfig() {
if (config == null) {
config = new Config();
@@ -22,8 +25,9 @@ public static Config getAsyncHttpClientConfig() {
* getAsyncHttpClientConfig() to get the new property values.
*/
public static void reloadProperties() {
- if (config != null)
+ if (config != null) {
config.reload();
+ }
}
public static class Config {
@@ -60,10 +64,12 @@ private Properties parsePropertiesFile(String file, boolean required) {
public String getString(String key) {
return propsCache.computeIfAbsent(key, k -> {
String value = System.getProperty(k);
- if (value == null)
+ if (value == null) {
value = customProperties.getProperty(k);
- if (value == null)
+ }
+ if (value == null) {
value = defaultProperties.getProperty(k);
+ }
return value;
});
}
@@ -76,8 +82,9 @@ public String[] getStringArray(String key) {
}
String[] rawArray = s.split(",");
String[] array = new String[rawArray.length];
- for (int i = 0; i < rawArray.length; i++)
+ for (int i = 0; i < rawArray.length; i++) {
array[i] = rawArray[i].trim();
+ }
return array;
}
diff --git a/client/src/main/java/org/asynchttpclient/cookie/ThreadSafeCookieStore.java b/client/src/main/java/org/asynchttpclient/cookie/ThreadSafeCookieStore.java
index 8f3fc44113..36f9ce27cc 100644
--- a/client/src/main/java/org/asynchttpclient/cookie/ThreadSafeCookieStore.java
+++ b/client/src/main/java/org/asynchttpclient/cookie/ThreadSafeCookieStore.java
@@ -51,15 +51,13 @@ public List get(Uri uri) {
@Override
public List getAll() {
- List result = cookieJar
+ return cookieJar
.values()
.stream()
.flatMap(map -> map.values().stream())
.filter(pair -> !hasCookieExpired(pair.cookie, pair.createdAt))
.map(pair -> pair.cookie)
.collect(Collectors.toList());
-
- return result;
}
@Override
@@ -110,60 +108,65 @@ public Map> getUnderlying() {
return new HashMap<>(cookieJar);
}
- private String requestDomain(Uri requestUri) {
+ private static String requestDomain(Uri requestUri) {
return requestUri.getHost().toLowerCase();
}
- private String requestPath(Uri requestUri) {
+ private static String requestPath(Uri requestUri) {
return requestUri.getPath().isEmpty() ? "/" : requestUri.getPath();
}
// rfc6265#section-5.2.3
// Let cookie-domain be the attribute-value without the leading %x2E (".") character.
- private AbstractMap.SimpleEntry cookieDomain(String cookieDomain, String requestDomain) {
+ private static AbstractMap.SimpleEntry cookieDomain(String cookieDomain, String requestDomain) {
if (cookieDomain != null) {
String normalizedCookieDomain = cookieDomain.toLowerCase();
return new AbstractMap.SimpleEntry<>(
- (!cookieDomain.isEmpty() && cookieDomain.charAt(0) == '.') ?
+ !cookieDomain.isEmpty() && cookieDomain.charAt(0) == '.' ?
normalizedCookieDomain.substring(1) :
normalizedCookieDomain, false);
- } else
+ } else {
return new AbstractMap.SimpleEntry<>(requestDomain, true);
+ }
}
// rfc6265#section-5.2.4
- private String cookiePath(String rawCookiePath, String requestPath) {
+ private static String cookiePath(String rawCookiePath, String requestPath) {
if (MiscUtils.isNonEmpty(rawCookiePath) && rawCookiePath.charAt(0) == '/') {
return rawCookiePath;
} else {
// rfc6265#section-5.1.4
int indexOfLastSlash = requestPath.lastIndexOf('/');
- if (!requestPath.isEmpty() && requestPath.charAt(0) == '/' && indexOfLastSlash > 0)
+ if (!requestPath.isEmpty() && requestPath.charAt(0) == '/' && indexOfLastSlash > 0) {
return requestPath.substring(0, indexOfLastSlash);
- else
+ } else {
return "/";
+ }
}
}
- private boolean hasCookieExpired(Cookie cookie, long whenCreated) {
+ private static boolean hasCookieExpired(Cookie cookie, long whenCreated) {
// if not specify max-age, this cookie should be discarded when user agent is to be closed, but it is not expired.
- if (cookie.maxAge() == Cookie.UNDEFINED_MAX_AGE)
+ if (cookie.maxAge() == Cookie.UNDEFINED_MAX_AGE) {
return false;
+ }
- if (cookie.maxAge() <= 0)
+ if (cookie.maxAge() <= 0) {
return true;
+ }
if (whenCreated > 0) {
long deltaSecond = (System.currentTimeMillis() - whenCreated) / 1000;
return deltaSecond > cookie.maxAge();
- } else
+ } else {
return false;
+ }
}
// rfc6265#section-5.1.4
- private boolean pathsMatch(String cookiePath, String requestPath) {
+ private static boolean pathsMatch(String cookiePath, String requestPath) {
return Objects.equals(cookiePath, requestPath) ||
- (requestPath.startsWith(cookiePath) && (cookiePath.charAt(cookiePath.length() - 1) == '/' || requestPath.charAt(cookiePath.length()) == '/'));
+ requestPath.startsWith(cookiePath) && (cookiePath.charAt(cookiePath.length() - 1) == '/' || requestPath.charAt(cookiePath.length()) == '/');
}
private void add(String requestDomain, String requestPath, Cookie cookie) {
@@ -173,9 +176,9 @@ private void add(String requestDomain, String requestPath, Cookie cookie) {
String keyPath = cookiePath(cookie.path(), requestPath);
CookieKey key = new CookieKey(cookie.name().toLowerCase(), keyPath);
- if (hasCookieExpired(cookie, 0))
+ if (hasCookieExpired(cookie, 0)) {
cookieJar.getOrDefault(keyDomain, Collections.emptyMap()).remove(key);
- else {
+ } else {
final Map innerMap = cookieJar.computeIfAbsent(keyDomain, domain -> new ConcurrentHashMap<>());
innerMap.put(key, new StoredCookie(cookie, hostOnly, cookie.maxAge() != Cookie.UNDEFINED_MAX_AGE));
}
@@ -241,15 +244,15 @@ private static class CookieKey implements Comparable {
public int compareTo(CookieKey o) {
Assertions.assertNotNull(o, "Parameter can't be null");
int result;
- if ((result = this.name.compareTo(o.name)) == 0)
- result = this.path.compareTo(o.path);
-
+ if ((result = name.compareTo(o.name)) == 0) {
+ result = path.compareTo(o.path);
+ }
return result;
}
@Override
public boolean equals(Object obj) {
- return obj instanceof CookieKey && this.compareTo((CookieKey) obj) == 0;
+ return obj instanceof CookieKey && compareTo((CookieKey) obj) == 0;
}
@Override
diff --git a/client/src/main/java/org/asynchttpclient/filter/FilterContext.java b/client/src/main/java/org/asynchttpclient/filter/FilterContext.java
index 6bf7a0dbe3..e12677f8b6 100644
--- a/client/src/main/java/org/asynchttpclient/filter/FilterContext.java
+++ b/client/src/main/java/org/asynchttpclient/filter/FilterContext.java
@@ -14,6 +14,7 @@
import io.netty.handler.codec.http.HttpHeaders;
import org.asynchttpclient.AsyncHandler;
+import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.HttpResponseStatus;
import org.asynchttpclient.Request;
@@ -28,72 +29,72 @@
*
* Invoking {@link FilterContext#getResponseStatus()} returns an instance of {@link HttpResponseStatus}
* that can be used to decide if the response processing should continue or not. You can stop the current response processing
- * and replay the request but creating a {@link FilterContext}. The {@link org.asynchttpclient.AsyncHttpClient}
+ * and replay the request but creating a {@link FilterContext}. The {@link AsyncHttpClient}
* will interrupt the processing and "replay" the associated {@link Request} instance.
*
* @param the handler result type
*/
public class FilterContext {
- private final FilterContextBuilder b;
+ private final FilterContextBuilder builder;
/**
* Create a new {@link FilterContext}
*
- * @param b a {@link FilterContextBuilder}
+ * @param builder a {@link FilterContextBuilder}
*/
- private FilterContext(FilterContextBuilder b) {
- this.b = b;
+ private FilterContext(FilterContextBuilder builder) {
+ this.builder = builder;
}
/**
* @return the original or decorated {@link AsyncHandler}
*/
public AsyncHandler getAsyncHandler() {
- return b.asyncHandler;
+ return builder.asyncHandler;
}
/**
* @return the original or decorated {@link Request}
*/
public Request getRequest() {
- return b.request;
+ return builder.request;
}
/**
* @return the unprocessed response's {@link HttpResponseStatus}
*/
public HttpResponseStatus getResponseStatus() {
- return b.responseStatus;
+ return builder.responseStatus;
}
/**
* @return the response {@link HttpHeaders}
*/
public HttpHeaders getResponseHeaders() {
- return b.headers;
+ return builder.headers;
}
/**
* @return true if the current response's processing needs to be interrupted and a new {@link Request} be executed.
*/
public boolean replayRequest() {
- return b.replayRequest;
+ return builder.replayRequest;
}
/**
* @return the {@link IOException}
*/
public IOException getIOException() {
- return b.ioException;
+ return builder.ioException;
}
public static class FilterContextBuilder {
- private AsyncHandler asyncHandler = null;
- private Request request = null;
- private HttpResponseStatus responseStatus = null;
- private boolean replayRequest = false;
- private IOException ioException = null;
+ private AsyncHandler asyncHandler;
+ private Request request;
+ private HttpResponseStatus responseStatus;
+ private boolean replayRequest;
+ private IOException ioException;
private HttpHeaders headers;
public FilterContextBuilder() {
@@ -149,5 +150,4 @@ public FilterContext build() {
return new FilterContext<>(this);
}
}
-
}
diff --git a/client/src/main/java/org/asynchttpclient/filter/FilterException.java b/client/src/main/java/org/asynchttpclient/filter/FilterException.java
index a90cf8494a..8d209211af 100644
--- a/client/src/main/java/org/asynchttpclient/filter/FilterException.java
+++ b/client/src/main/java/org/asynchttpclient/filter/FilterException.java
@@ -12,8 +12,10 @@
*/
package org.asynchttpclient.filter;
+import org.asynchttpclient.AsyncHandler;
+
/**
- * An exception that can be thrown by an {@link org.asynchttpclient.AsyncHandler} to interrupt invocation of
+ * An exception that can be thrown by an {@link AsyncHandler} to interrupt invocation of
* the {@link RequestFilter} and {@link ResponseFilter}. It also interrupt the request and response processing.
*/
@SuppressWarnings("serial")
diff --git a/client/src/main/java/org/asynchttpclient/filter/IOExceptionFilter.java b/client/src/main/java/org/asynchttpclient/filter/IOExceptionFilter.java
index 71f45b5b47..a7df377172 100644
--- a/client/src/main/java/org/asynchttpclient/filter/IOExceptionFilter.java
+++ b/client/src/main/java/org/asynchttpclient/filter/IOExceptionFilter.java
@@ -12,14 +12,19 @@
*/
package org.asynchttpclient.filter;
+import org.asynchttpclient.AsyncHttpClient;
+import org.asynchttpclient.Request;
+
+import java.io.IOException;
+
/**
- * This filter is invoked when an {@link java.io.IOException} occurs during an http transaction.
+ * This filter is invoked when an {@link IOException} occurs during an http transaction.
*/
public interface IOExceptionFilter {
/**
- * An {@link org.asynchttpclient.AsyncHttpClient} will invoke {@link IOExceptionFilter#filter} and will
- * use the returned {@link FilterContext} to replay the {@link org.asynchttpclient.Request} or abort the processing.
+ * An {@link AsyncHttpClient} will invoke {@link IOExceptionFilter#filter} and will
+ * use the returned {@link FilterContext} to replay the {@link Request} or abort the processing.
*
* @param ctx a {@link FilterContext}
* @param the handler result type
diff --git a/client/src/main/java/org/asynchttpclient/filter/ReleasePermitOnComplete.java b/client/src/main/java/org/asynchttpclient/filter/ReleasePermitOnComplete.java
index bbed05cc48..0e8c3de5fa 100644
--- a/client/src/main/java/org/asynchttpclient/filter/ReleasePermitOnComplete.java
+++ b/client/src/main/java/org/asynchttpclient/filter/ReleasePermitOnComplete.java
@@ -11,7 +11,11 @@
/**
* Wrapper for {@link AsyncHandler}s to release a permit on {@link AsyncHandler#onCompleted()}. This is done via a dynamic proxy to preserve all interfaces of the wrapped handler.
*/
-public class ReleasePermitOnComplete {
+public final class ReleasePermitOnComplete {
+
+ private ReleasePermitOnComplete() {
+ // Prevent outside initialization
+ }
/**
* Wrap handler to release the permit of the semaphore on {@link AsyncHandler#onCompleted()}.
diff --git a/client/src/main/java/org/asynchttpclient/filter/RequestFilter.java b/client/src/main/java/org/asynchttpclient/filter/RequestFilter.java
index 7b3838c439..8b2a6fd9d1 100644
--- a/client/src/main/java/org/asynchttpclient/filter/RequestFilter.java
+++ b/client/src/main/java/org/asynchttpclient/filter/RequestFilter.java
@@ -12,13 +12,15 @@
*/
package org.asynchttpclient.filter;
+import org.asynchttpclient.AsyncHttpClient;
+
/**
* A Filter interface that gets invoked before making an actual request.
*/
public interface RequestFilter {
/**
- * An {@link org.asynchttpclient.AsyncHttpClient} will invoke {@link RequestFilter#filter} and will use the
+ * An {@link AsyncHttpClient} will invoke {@link RequestFilter#filter} and will use the
* returned {@link FilterContext#getRequest()} and {@link FilterContext#getAsyncHandler()} to continue the request
* processing.
*
diff --git a/client/src/main/java/org/asynchttpclient/filter/ResponseFilter.java b/client/src/main/java/org/asynchttpclient/filter/ResponseFilter.java
index 404d9ee097..3fd9ffb236 100644
--- a/client/src/main/java/org/asynchttpclient/filter/ResponseFilter.java
+++ b/client/src/main/java/org/asynchttpclient/filter/ResponseFilter.java
@@ -12,6 +12,8 @@
*/
package org.asynchttpclient.filter;
+import org.asynchttpclient.AsyncHttpClient;
+
/**
* A Filter interface that gets invoked before making the processing of the response bytes. {@link ResponseFilter} are invoked
* before the actual response's status code get processed. That means authorization, proxy authentication and redirects
@@ -20,7 +22,7 @@
public interface ResponseFilter {
/**
- * An {@link org.asynchttpclient.AsyncHttpClient} will invoke {@link ResponseFilter#filter} and will use the
+ * An {@link AsyncHttpClient} will invoke {@link ResponseFilter#filter} and will use the
* returned {@link FilterContext#replayRequest()} and {@link FilterContext#getAsyncHandler()} to decide if the response
* processing can continue. If {@link FilterContext#replayRequest()} return true, a new request will be made
* using {@link FilterContext#getRequest()} and the current response processing will be ignored.
diff --git a/client/src/main/java/org/asynchttpclient/filter/ThrottleRequestFilter.java b/client/src/main/java/org/asynchttpclient/filter/ThrottleRequestFilter.java
index 6b7565bad2..9b5225198d 100644
--- a/client/src/main/java/org/asynchttpclient/filter/ThrottleRequestFilter.java
+++ b/client/src/main/java/org/asynchttpclient/filter/ThrottleRequestFilter.java
@@ -19,7 +19,7 @@
import java.util.concurrent.TimeUnit;
/**
- * A {@link org.asynchttpclient.filter.RequestFilter} throttles requests and block when the number of permits is reached,
+ * A {@link RequestFilter} throttles requests and block when the number of permits is reached,
* waiting for the response to arrives before executing the next request.
*/
public class ThrottleRequestFilter implements RequestFilter {
@@ -40,9 +40,6 @@ public ThrottleRequestFilter(int maxConnections, int maxWait, boolean fair) {
available = new Semaphore(maxConnections, fair);
}
- /**
- * {@inheritDoc}
- */
@Override
public FilterContext filter(FilterContext ctx) throws FilterException {
try {
@@ -50,12 +47,10 @@ public FilterContext filter(FilterContext ctx) throws FilterException
logger.debug("Current Throttling Status {}", available.availablePermits());
}
if (!available.tryAcquire(maxWait, TimeUnit.MILLISECONDS)) {
- throw new FilterException(String.format("No slot available for processing Request %s with AsyncHandler %s",
- ctx.getRequest(), ctx.getAsyncHandler()));
+ throw new FilterException(String.format("No slot available for processing Request %s with AsyncHandler %s", ctx.getRequest(), ctx.getAsyncHandler()));
}
} catch (InterruptedException e) {
- throw new FilterException(String.format("Interrupted Request %s with AsyncHandler %s",
- ctx.getRequest(), ctx.getAsyncHandler()));
+ throw new FilterException(String.format("Interrupted Request %s with AsyncHandler %s", ctx.getRequest(), ctx.getAsyncHandler()));
}
return new FilterContext.FilterContextBuilder<>(ctx)
diff --git a/client/src/main/java/org/asynchttpclient/handler/BodyDeferringAsyncHandler.java b/client/src/main/java/org/asynchttpclient/handler/BodyDeferringAsyncHandler.java
index 984479c0dd..304998944b 100644
--- a/client/src/main/java/org/asynchttpclient/handler/BodyDeferringAsyncHandler.java
+++ b/client/src/main/java/org/asynchttpclient/handler/BodyDeferringAsyncHandler.java
@@ -36,7 +36,7 @@
* long as headers are received, and return Response as soon as possible, but
* still pouring response body into supplied output stream. This handler is
* meant for situations when the "recommended" way (using
- * client.prepareGet("http://foo.com/aResource").execute().get()
+ * {@code client.prepareGet("http://foo.com/aResource").execute().get()}
* would not work for you, since a potentially large response body is about to
* be GETted, but you need headers first, or you don't know yet (depending on
* some logic, maybe coming from headers) where to save the body, or you just
@@ -92,13 +92,13 @@ public class BodyDeferringAsyncHandler implements AsyncHandler {
private volatile Throwable throwable;
public BodyDeferringAsyncHandler(final OutputStream os) {
- this.output = os;
- this.responseSet = false;
+ output = os;
+ responseSet = false;
}
@Override
public void onThrowable(Throwable t) {
- this.throwable = t;
+ throwable = t;
// Counting down to handle error cases too.
// In "premature exceptions" cases, the onBodyPartReceived() and
// onCompleted()
@@ -141,7 +141,7 @@ public State onTrailingHeadersReceived(HttpHeaders headers) {
@Override
public void onRetry() {
- throw new UnsupportedOperationException(this.getClass().getSimpleName() + " cannot retry a request.");
+ throw new UnsupportedOperationException(getClass().getSimpleName() + " cannot retry a request.");
}
@Override
@@ -210,7 +210,7 @@ public Response onCompleted() throws IOException {
* 1st cached, probably incomplete one. Note: the response returned by this
* method will contain everything except the response body itself,
* so invoking any method like Response.getResponseBodyXXX() will result in
- * error! Also, please not that this method might return null
+ * error! Also, please not that this method might return {@code null}
* in case of some errors.
*
* @return a {@link Response}
@@ -271,7 +271,7 @@ public void close() throws IOException {
/**
* Delegates to {@link BodyDeferringAsyncHandler#getResponse()}. Will
* blocks as long as headers arrives only. Might return
- * null. See
+ * {@code null}. See
* {@link BodyDeferringAsyncHandler#getResponse()} method for details.
*
* @return a {@link Response}
@@ -283,7 +283,7 @@ public Response getAsapResponse() throws InterruptedException, IOException {
}
/**
- * Delegates to Future$lt;Response>#get() method. Will block
+ * Delegates to {@code Future$lt;Response>#get()} method. Will block
* as long as complete response arrives.
*
* @return a {@link Response}
@@ -294,4 +294,4 @@ public Response getLastResponse() throws InterruptedException, ExecutionExceptio
return future.get();
}
}
-}
\ No newline at end of file
+}
diff --git a/client/src/main/java/org/asynchttpclient/handler/MaxRedirectException.java b/client/src/main/java/org/asynchttpclient/handler/MaxRedirectException.java
index e88882e2bd..30eefff768 100644
--- a/client/src/main/java/org/asynchttpclient/handler/MaxRedirectException.java
+++ b/client/src/main/java/org/asynchttpclient/handler/MaxRedirectException.java
@@ -13,8 +13,10 @@
*/
package org.asynchttpclient.handler;
+import org.asynchttpclient.DefaultAsyncHttpClientConfig;
+
/**
- * Thrown when the {@link org.asynchttpclient.DefaultAsyncHttpClientConfig#getMaxRedirects()} has been reached.
+ * Thrown when the {@link DefaultAsyncHttpClientConfig#getMaxRedirects()} has been reached.
*/
public class MaxRedirectException extends Exception {
private static final long serialVersionUID = 1L;
diff --git a/client/src/main/java/org/asynchttpclient/handler/ProgressAsyncHandler.java b/client/src/main/java/org/asynchttpclient/handler/ProgressAsyncHandler.java
index e46fcea106..50100e3bf4 100644
--- a/client/src/main/java/org/asynchttpclient/handler/ProgressAsyncHandler.java
+++ b/client/src/main/java/org/asynchttpclient/handler/ProgressAsyncHandler.java
@@ -15,6 +15,9 @@
import org.asynchttpclient.AsyncHandler;
import org.asynchttpclient.Request;
+import java.io.File;
+import java.io.FileInputStream;
+
/**
* An extended {@link AsyncHandler} with two extra callback who get invoked during the content upload to a remote server.
* This {@link AsyncHandler} must be used only with PUT and POST request.
@@ -22,7 +25,7 @@
public interface ProgressAsyncHandler extends AsyncHandler {
/**
- * Invoked when the content (a {@link java.io.File}, {@link String} or {@link java.io.FileInputStream} has been fully
+ * Invoked when the content (a {@link File}, {@link String} or {@link FileInputStream} has been fully
* written on the I/O socket.
*
* @return a {@link AsyncHandler.State} telling to CONTINUE or ABORT the current processing.
@@ -30,7 +33,7 @@ public interface ProgressAsyncHandler extends AsyncHandler {
State onHeadersWritten();
/**
- * Invoked when the content (a {@link java.io.File}, {@link String} or {@link java.io.FileInputStream} has been fully
+ * Invoked when the content (a {@link File}, {@link String} or {@link FileInputStream} has been fully
* written on the I/O socket.
*
* @return a {@link AsyncHandler.State} telling to CONTINUE or ABORT the current processing.
diff --git a/client/src/main/java/org/asynchttpclient/handler/TransferCompletionHandler.java b/client/src/main/java/org/asynchttpclient/handler/TransferCompletionHandler.java
index 8b2801b473..85b0ded155 100644
--- a/client/src/main/java/org/asynchttpclient/handler/TransferCompletionHandler.java
+++ b/client/src/main/java/org/asynchttpclient/handler/TransferCompletionHandler.java
@@ -14,6 +14,7 @@
import io.netty.handler.codec.http.HttpHeaders;
import org.asynchttpclient.AsyncCompletionHandlerBase;
+import org.asynchttpclient.AsyncHandler;
import org.asynchttpclient.HttpResponseBodyPart;
import org.asynchttpclient.Response;
import org.slf4j.Logger;
@@ -22,7 +23,7 @@
import java.util.concurrent.ConcurrentLinkedQueue;
/**
- * A {@link org.asynchttpclient.AsyncHandler} that can be used to notify a set of {@link TransferListener}
+ * A {@link AsyncHandler} that can be used to notify a set of {@link TransferListener}
*
*
*
@@ -54,21 +55,22 @@
*
*/
public class TransferCompletionHandler extends AsyncCompletionHandlerBase {
- private final static Logger logger = LoggerFactory.getLogger(TransferCompletionHandler.class);
+ private static final Logger logger = LoggerFactory.getLogger(TransferCompletionHandler.class);
+
private final ConcurrentLinkedQueue listeners = new ConcurrentLinkedQueue<>();
private final boolean accumulateResponseBytes;
private HttpHeaders headers;
/**
- * Create a TransferCompletionHandler that will not accumulate bytes. The resulting {@link org.asynchttpclient.Response#getResponseBody()},
- * {@link org.asynchttpclient.Response#getResponseBodyAsStream()} will throw an IllegalStateException if called.
+ * Create a TransferCompletionHandler that will not accumulate bytes. The resulting {@link Response#getResponseBody()},
+ * {@link Response#getResponseBodyAsStream()} will throw an IllegalStateException if called.
*/
public TransferCompletionHandler() {
this(false);
}
/**
- * Create a TransferCompletionHandler that can or cannot accumulate bytes and make it available when {@link org.asynchttpclient.Response#getResponseBody()} get called. The
+ * Create a TransferCompletionHandler that can or cannot accumulate bytes and make it available when {@link Response#getResponseBody()} get called. The
* default is false.
*
* @param accumulateResponseBytes true to accumulates bytes in memory.
diff --git a/client/src/main/java/org/asynchttpclient/handler/TransferListener.java b/client/src/main/java/org/asynchttpclient/handler/TransferListener.java
index 0ced1c546e..c3921f1a01 100644
--- a/client/src/main/java/org/asynchttpclient/handler/TransferListener.java
+++ b/client/src/main/java/org/asynchttpclient/handler/TransferListener.java
@@ -36,7 +36,7 @@ public interface TransferListener {
/**
* Invoked every time response's chunk are received.
*
- * @param bytes a {@link byte[]}
+ * @param bytes a {@link byte} array
*/
void onBytesReceived(byte[] bytes);
diff --git a/client/src/main/java/org/asynchttpclient/handler/resumable/PropertiesBasedResumableProcessor.java b/client/src/main/java/org/asynchttpclient/handler/resumable/PropertiesBasedResumableProcessor.java
index 45508e5d62..3a65f019e7 100644
--- a/client/src/main/java/org/asynchttpclient/handler/resumable/PropertiesBasedResumableProcessor.java
+++ b/client/src/main/java/org/asynchttpclient/handler/resumable/PropertiesBasedResumableProcessor.java
@@ -19,6 +19,7 @@
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.nio.file.Files;
+import java.util.Collections;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ConcurrentHashMap;
@@ -27,30 +28,25 @@
import static org.asynchttpclient.util.MiscUtils.closeSilently;
/**
- * A {@link org.asynchttpclient.handler.resumable.ResumableAsyncHandler.ResumableProcessor} which use a properties file
+ * A {@link ResumableAsyncHandler.ResumableProcessor} which use a properties file
* to store the download index information.
*/
public class PropertiesBasedResumableProcessor implements ResumableAsyncHandler.ResumableProcessor {
- private final static Logger log = LoggerFactory.getLogger(PropertiesBasedResumableProcessor.class);
- private final static File TMP = new File(System.getProperty("java.io.tmpdir"), "ahc");
- private final static String storeName = "ResumableAsyncHandler.properties";
+ private static final Logger log = LoggerFactory.getLogger(PropertiesBasedResumableProcessor.class);
+ private static final File TMP = new File(System.getProperty("java.io.tmpdir"), "ahc");
+ private static final String storeName = "ResumableAsyncHandler.properties";
+
private final ConcurrentHashMap properties = new ConcurrentHashMap<>();
private static String append(Map.Entry e) {
return e.getKey() + '=' + e.getValue() + '\n';
}
- /**
- * {@inheritDoc}
- */
@Override
public void put(String url, long transferredBytes) {
properties.put(url, transferredBytes);
}
- /**
- * {@inheritDoc}
- */
@Override
public void remove(String uri) {
if (uri != null) {
@@ -58,12 +54,9 @@ public void remove(String uri) {
}
}
- /**
- * {@inheritDoc}
- */
@Override
public void save(Map map) {
- log.debug("Saving current download state {}", properties.toString());
+ log.debug("Saving current download state {}", properties);
OutputStream os = null;
try {
@@ -90,14 +83,11 @@ public void save(Map map) {
}
}
- /**
- * {@inheritDoc}
- */
@Override
public Map load() {
Scanner scan = null;
try {
- scan = new Scanner(new File(TMP, storeName), UTF_8.name());
+ scan = new Scanner(new File(TMP, storeName), UTF_8);
scan.useDelimiter("[=\n]");
String key;
@@ -107,16 +97,17 @@ public Map load() {
value = scan.next().trim();
properties.put(key, Long.valueOf(value));
}
- log.debug("Loading previous download state {}", properties.toString());
+ log.debug("Loading previous download state {}", properties);
} catch (FileNotFoundException ex) {
log.debug("Missing {}", storeName);
} catch (Throwable ex) {
// Survive any exceptions
log.warn(ex.getMessage(), ex);
} finally {
- if (scan != null)
+ if (scan != null) {
scan.close();
+ }
}
- return properties;
+ return Collections.unmodifiableMap(properties);
}
}
diff --git a/client/src/main/java/org/asynchttpclient/handler/resumable/ResumableAsyncHandler.java b/client/src/main/java/org/asynchttpclient/handler/resumable/ResumableAsyncHandler.java
index 8b3f140c35..3cef60a7c4 100644
--- a/client/src/main/java/org/asynchttpclient/handler/resumable/ResumableAsyncHandler.java
+++ b/client/src/main/java/org/asynchttpclient/handler/resumable/ResumableAsyncHandler.java
@@ -37,7 +37,7 @@
/**
* An {@link AsyncHandler} which support resumable download, e.g when used with an {@link ResumableIOExceptionFilter},
* this handler can resume the download operation at the point it was before the interruption occurred. This prevent having to
- * download the entire file again. It's the responsibility of the {@link org.asynchttpclient.handler.resumable.ResumableAsyncHandler}
+ * download the entire file again. It's the responsibility of the {@link ResumableAsyncHandler}
* to track how many bytes has been transferred and to properly adjust the file's write position.
*
* In case of a JVM crash/shutdown, you can create an instance of this class and pass the last valid bytes position.
@@ -45,15 +45,16 @@
* Beware that it registers a shutdown hook, that will cause a ClassLoader leak when used in an appserver and only redeploying the application.
*/
public class ResumableAsyncHandler implements AsyncHandler {
- private final static Logger logger = LoggerFactory.getLogger(TransferCompletionHandler.class);
- private final static ResumableIndexThread resumeIndexThread = new ResumableIndexThread();
+ private static final Logger logger = LoggerFactory.getLogger(TransferCompletionHandler.class);
+ private static final ResumableIndexThread resumeIndexThread = new ResumableIndexThread();
private static Map resumableIndex;
+
private final AtomicLong byteTransferred;
private final ResumableProcessor resumableProcessor;
private final AsyncHandler decoratedAsyncHandler;
private final boolean accumulateBody;
private String url;
- private ResponseBuilder responseBuilder = new ResponseBuilder();
+ private final ResponseBuilder responseBuilder = new ResponseBuilder();
private ResumableListener resumableListener = new NULLResumableListener();
private ResumableAsyncHandler(long byteTransferred, ResumableProcessor resumableProcessor,
@@ -192,7 +193,6 @@ public State onTrailingHeadersReceived(HttpHeaders headers) {
* @return a {@link Request} with the Range header properly set.
*/
public Request adjustRequestRange(Request request) {
-
Long ri = resumableIndex.get(request.getUrl());
if (ri != null) {
byteTransferred.set(ri);
@@ -205,7 +205,7 @@ public Request adjustRequestRange(Request request) {
RequestBuilder builder = request.toBuilder();
if (request.getHeaders().get(RANGE) == null && byteTransferred.get() != 0) {
- builder.setHeader(RANGE, "bytes=" + byteTransferred.get() + "-");
+ builder.setHeader(RANGE, "bytes=" + byteTransferred.get() + '-');
}
return builder.build();
}
@@ -255,14 +255,13 @@ public interface ResumableProcessor {
* @return {@link Map} current transfer state
*/
Map load();
-
}
private static class ResumableIndexThread extends Thread {
public final ConcurrentLinkedQueue resumableProcessors = new ConcurrentLinkedQueue<>();
- public ResumableIndexThread() {
+ private ResumableIndexThread() {
Runtime.getRuntime().addShutdownHook(this);
}
@@ -270,6 +269,7 @@ public void addResumableProcessor(ResumableProcessor p) {
resumableProcessors.offer(p);
}
+ @Override
public void run() {
for (ResumableProcessor p : resumableProcessors) {
p.save(resumableIndex);
@@ -279,15 +279,19 @@ public void run() {
private static class NULLResumableHandler implements ResumableProcessor {
+ @Override
public void put(String url, long transferredBytes) {
}
+ @Override
public void remove(String uri) {
}
+ @Override
public void save(Map map) {
}
+ @Override
public Map load() {
return new HashMap<>();
}
@@ -295,15 +299,22 @@ public Map load() {
private static class NULLResumableListener implements ResumableListener {
- private long length = 0L;
+ private long length;
+
+ private NULLResumableListener() {
+ length = 0L;
+ }
+ @Override
public void onBytesReceived(ByteBuffer byteBuffer) {
length += byteBuffer.remaining();
}
+ @Override
public void onAllBytesReceived() {
}
+ @Override
public long length() {
return length;
}
diff --git a/client/src/main/java/org/asynchttpclient/handler/resumable/ResumableIOExceptionFilter.java b/client/src/main/java/org/asynchttpclient/handler/resumable/ResumableIOExceptionFilter.java
index b2c87f6f3e..190ec6a3a7 100644
--- a/client/src/main/java/org/asynchttpclient/handler/resumable/ResumableIOExceptionFilter.java
+++ b/client/src/main/java/org/asynchttpclient/handler/resumable/ResumableIOExceptionFilter.java
@@ -17,14 +17,14 @@
import org.asynchttpclient.filter.IOExceptionFilter;
/**
- * Simple {@link org.asynchttpclient.filter.IOExceptionFilter} that replay the current {@link org.asynchttpclient.Request} using a {@link ResumableAsyncHandler}
+ * Simple {@link IOExceptionFilter} that replay the current {@link Request} using a {@link ResumableAsyncHandler}
*/
public class ResumableIOExceptionFilter implements IOExceptionFilter {
+
+ @Override
public FilterContext filter(FilterContext ctx) {
if (ctx.getIOException() != null && ctx.getAsyncHandler() instanceof ResumableAsyncHandler) {
-
- Request request = ResumableAsyncHandler.class.cast(ctx.getAsyncHandler()).adjustRequestRange(ctx.getRequest());
-
+ Request request = ((ResumableAsyncHandler) ctx.getAsyncHandler()).adjustRequestRange(ctx.getRequest());
return new FilterContext.FilterContextBuilder<>(ctx).request(request).replayRequest(true).build();
}
return ctx;
diff --git a/client/src/main/java/org/asynchttpclient/handler/resumable/ResumableRandomAccessFileListener.java b/client/src/main/java/org/asynchttpclient/handler/resumable/ResumableRandomAccessFileListener.java
index 1a64b1b61f..f7e28f6f64 100644
--- a/client/src/main/java/org/asynchttpclient/handler/resumable/ResumableRandomAccessFileListener.java
+++ b/client/src/main/java/org/asynchttpclient/handler/resumable/ResumableRandomAccessFileListener.java
@@ -19,7 +19,7 @@
import static org.asynchttpclient.util.MiscUtils.closeSilently;
/**
- * A {@link org.asynchttpclient.handler.resumable.ResumableListener} which use a {@link RandomAccessFile} for storing the received bytes.
+ * A {@link ResumableListener} which use a {@link RandomAccessFile} for storing the received bytes.
*/
public class ResumableRandomAccessFileListener implements ResumableListener {
private final RandomAccessFile file;
@@ -35,6 +35,7 @@ public ResumableRandomAccessFileListener(RandomAccessFile file) {
* @param buffer a {@link ByteBuffer}
* @throws IOException exception while writing into the file
*/
+ @Override
public void onBytesReceived(ByteBuffer buffer) throws IOException {
file.seek(file.length());
if (buffer.hasArray()) {
@@ -48,21 +49,17 @@ public void onBytesReceived(ByteBuffer buffer) throws IOException {
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public void onAllBytesReceived() {
closeSilently(file);
}
- /**
- * {@inheritDoc}
- */
+ @Override
public long length() {
try {
return file.length();
} catch (IOException e) {
- return 0;
+ return -1;
}
}
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/EagerResponseBodyPart.java b/client/src/main/java/org/asynchttpclient/netty/EagerResponseBodyPart.java
index ff3144f22a..51c55c0399 100755
--- a/client/src/main/java/org/asynchttpclient/netty/EagerResponseBodyPart.java
+++ b/client/src/main/java/org/asynchttpclient/netty/EagerResponseBodyPart.java
@@ -13,12 +13,11 @@
package org.asynchttpclient.netty;
import io.netty.buffer.ByteBuf;
+import io.netty.buffer.ByteBufUtil;
import org.asynchttpclient.HttpResponseBodyPart;
import java.nio.ByteBuffer;
-import static org.asynchttpclient.netty.util.ByteBufUtils.byteBuf2Bytes;
-
/**
* A callback class used when an HTTP response body is received.
* Bytes are eagerly fetched from the ByteBuf
@@ -29,7 +28,7 @@ public class EagerResponseBodyPart extends HttpResponseBodyPart {
public EagerResponseBodyPart(ByteBuf buf, boolean last) {
super(last);
- bytes = byteBuf2Bytes(buf);
+ bytes = ByteBufUtil.getBytes(buf);
}
/**
diff --git a/client/src/main/java/org/asynchttpclient/netty/LazyResponseBodyPart.java b/client/src/main/java/org/asynchttpclient/netty/LazyResponseBodyPart.java
index b1432268fd..2dc9613a84 100755
--- a/client/src/main/java/org/asynchttpclient/netty/LazyResponseBodyPart.java
+++ b/client/src/main/java/org/asynchttpclient/netty/LazyResponseBodyPart.java
@@ -13,8 +13,8 @@
package org.asynchttpclient.netty;
import io.netty.buffer.ByteBuf;
+import io.netty.buffer.ByteBufUtil;
import org.asynchttpclient.HttpResponseBodyPart;
-import org.asynchttpclient.netty.util.ByteBufUtils;
import java.nio.ByteBuffer;
@@ -46,7 +46,7 @@ public int length() {
*/
@Override
public byte[] getBodyPartBytes() {
- return ByteBufUtils.byteBuf2Bytes(buf.duplicate());
+ return ByteBufUtil.getBytes(buf.duplicate());
}
@Override
diff --git a/client/src/main/java/org/asynchttpclient/netty/NettyResponse.java b/client/src/main/java/org/asynchttpclient/netty/NettyResponse.java
index 5d97bdfc18..1357f95e77 100755
--- a/client/src/main/java/org/asynchttpclient/netty/NettyResponse.java
+++ b/client/src/main/java/org/asynchttpclient/netty/NettyResponse.java
@@ -32,14 +32,16 @@
import java.util.List;
import java.util.Map;
-import static io.netty.handler.codec.http.HttpHeaderNames.*;
+import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
+import static io.netty.handler.codec.http.HttpHeaderNames.SET_COOKIE;
+import static io.netty.handler.codec.http.HttpHeaderNames.SET_COOKIE2;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.asynchttpclient.util.HttpUtils.extractContentTypeCharsetAttribute;
import static org.asynchttpclient.util.MiscUtils.isNonEmpty;
import static org.asynchttpclient.util.MiscUtils.withDefault;
/**
- * Wrapper around the {@link org.asynchttpclient.Response} API.
+ * Wrapper around the {@link Response} API.
*/
public class NettyResponse implements Response {
@@ -68,8 +70,9 @@ private List buildCookies() {
List cookies = new ArrayList<>(1);
for (String value : setCookieHeaders) {
Cookie c = ClientCookieDecoder.STRICT.decode(value);
- if (c != null)
+ if (c != null) {
cookies.add(c);
+ }
}
return Collections.unmodifiableList(cookies);
}
@@ -174,12 +177,14 @@ public byte[] getResponseBodyAsBytes() {
public ByteBuffer getResponseBodyAsByteBuffer() {
int length = 0;
- for (HttpResponseBodyPart part : bodyParts)
+ for (HttpResponseBodyPart part : bodyParts) {
length += part.length();
+ }
ByteBuffer target = ByteBuffer.wrap(new byte[length]);
- for (HttpResponseBodyPart part : bodyParts)
+ for (HttpResponseBodyPart part : bodyParts) {
target.put(part.getBodyPartBytes());
+ }
target.flip();
return target;
@@ -204,13 +209,13 @@ public InputStream getResponseBodyAsStream() {
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()).append(" {\n")
- .append("\tstatusCode=").append(getStatusCode()).append("\n")
+ .append("\tstatusCode=").append(getStatusCode()).append('\n')
.append("\theaders=\n");
for (Map.Entry header : getHeaders()) {
- sb.append("\t\t").append(header.getKey()).append(": ").append(header.getValue()).append("\n");
+ sb.append("\t\t").append(header.getKey()).append(": ").append(header.getValue()).append('\n');
}
- return sb.append("\tbody=\n").append(getResponseBody()).append("\n")
- .append("}").toString();
+ return sb.append("\tbody=\n").append(getResponseBody()).append('\n')
+ .append('}').toString();
}
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/NettyResponseFuture.java b/client/src/main/java/org/asynchttpclient/netty/NettyResponseFuture.java
index f60aec8681..b4d32cabb4 100755
--- a/client/src/main/java/org/asynchttpclient/netty/NettyResponseFuture.java
+++ b/client/src/main/java/org/asynchttpclient/netty/NettyResponseFuture.java
@@ -92,21 +92,21 @@ public final class NettyResponseFuture implements ListenableFuture {
public Throwable pendingException;
// state mutated from outside the event loop
// TODO check if they are indeed mutated outside the event loop
- private volatile int isDone = 0;
- private volatile int isCancelled = 0;
- private volatile int inAuth = 0;
- private volatile int inProxyAuth = 0;
+ private volatile int isDone;
+ private volatile int isCancelled;
+ private volatile int inAuth;
+ private volatile int inProxyAuth;
@SuppressWarnings("unused")
- private volatile int contentProcessed = 0;
+ private volatile int contentProcessed;
@SuppressWarnings("unused")
- private volatile int onThrowableCalled = 0;
+ private volatile int onThrowableCalled;
@SuppressWarnings("unused")
private volatile TimeoutsHolder timeoutsHolder;
// partition key, when != null used to release lock in ChannelManager
private volatile Object partitionKeyLock;
// volatile where we need CAS ops
- private volatile int redirectCount = 0;
- private volatile int currentRetry = 0;
+ private volatile int redirectCount;
+ private volatile int currentRetry;
// volatile where we don't need CAS ops
private volatile long touch = unpreciseMillisTime();
private volatile ChannelState channelState = ChannelState.NEW;
@@ -134,7 +134,7 @@ public NettyResponseFuture(Request originalRequest,
ProxyServer proxyServer) {
this.asyncHandler = asyncHandler;
- this.targetRequest = currentRequest = originalRequest;
+ targetRequest = currentRequest = originalRequest;
this.nettyRequest = nettyRequest;
this.connectionPoolPartitioning = connectionPoolPartitioning;
this.connectionSemaphore = connectionSemaphore;
@@ -181,8 +181,9 @@ public boolean cancel(boolean force) {
releasePartitionKeyLock();
cancelTimeouts();
- if (IS_CANCELLED_FIELD.getAndSet(this, 1) != 0)
+ if (IS_CANCELLED_FIELD.getAndSet(this, 1) != 0) {
return false;
+ }
// cancel could happen before channel was attached
if (channel != null) {
@@ -249,15 +250,17 @@ private void loadContent() throws ExecutionException {
private boolean terminateAndExit() {
releasePartitionKeyLock();
cancelTimeouts();
- this.channel = null;
- this.reuseChannel = false;
+ channel = null;
+ reuseChannel = false;
return IS_DONE_FIELD.getAndSet(this, 1) != 0 || isCancelled != 0;
}
- public final void done() {
+ @Override
+ public void done() {
- if (terminateAndExit())
+ if (terminateAndExit()) {
return;
+ }
try {
loadContent();
@@ -271,10 +274,12 @@ public final void done() {
}
}
- public final void abort(final Throwable t) {
+ @Override
+ public void abort(final Throwable t) {
- if (terminateAndExit())
+ if (terminateAndExit()) {
return;
+ }
future.completeExceptionally(t);
@@ -323,7 +328,7 @@ public void cancelTimeouts() {
}
}
- public final Request getTargetRequest() {
+ public Request getTargetRequest() {
return targetRequest;
}
@@ -331,7 +336,7 @@ public void setTargetRequest(Request targetRequest) {
this.targetRequest = targetRequest;
}
- public final Request getCurrentRequest() {
+ public Request getCurrentRequest() {
return currentRequest;
}
@@ -339,15 +344,15 @@ public void setCurrentRequest(Request currentRequest) {
this.currentRequest = currentRequest;
}
- public final NettyRequest getNettyRequest() {
+ public NettyRequest getNettyRequest() {
return nettyRequest;
}
- public final void setNettyRequest(NettyRequest nettyRequest) {
+ public void setNettyRequest(NettyRequest nettyRequest) {
this.nettyRequest = nettyRequest;
}
- public final AsyncHandler getAsyncHandler() {
+ public AsyncHandler getAsyncHandler() {
return asyncHandler;
}
@@ -355,11 +360,11 @@ public void setAsyncHandler(AsyncHandler asyncHandler) {
this.asyncHandler = asyncHandler;
}
- public final boolean isKeepAlive() {
+ public boolean isKeepAlive() {
return keepAlive;
}
- public final void setKeepAlive(final boolean keepAlive) {
+ public void setKeepAlive(final boolean keepAlive) {
this.keepAlive = keepAlive;
}
@@ -415,7 +420,7 @@ public boolean isStreamConsumed() {
}
public void setStreamConsumed(boolean streamConsumed) {
- this.streamAlreadyConsumed = streamConsumed;
+ streamAlreadyConsumed = streamConsumed;
}
public long getLastTouch() {
@@ -481,7 +486,7 @@ public boolean incrementRetryAndCheck() {
* @return true if that {@link Future} cannot be recovered.
*/
public boolean isReplayPossible() {
- return !isDone() && !(Channels.isChannelActive(channel) && !getUri().getScheme().equalsIgnoreCase("https"))
+ return !isDone() && !(Channels.isChannelActive(channel) && !"https".equalsIgnoreCase(getUri().getScheme()))
&& inAuth == 0 && inProxyAuth == 0;
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/NettyResponseStatus.java b/client/src/main/java/org/asynchttpclient/netty/NettyResponseStatus.java
index 6a5a31a5ff..4ebf3092d5 100755
--- a/client/src/main/java/org/asynchttpclient/netty/NettyResponseStatus.java
+++ b/client/src/main/java/org/asynchttpclient/netty/NettyResponseStatus.java
@@ -46,6 +46,7 @@ public NettyResponseStatus(Uri uri, HttpResponse response, Channel channel) {
*
* @return the response status code
*/
+ @Override
public int getStatusCode() {
return response.status().code();
}
@@ -55,6 +56,7 @@ public int getStatusCode() {
*
* @return the response status text
*/
+ @Override
public String getStatusText() {
return response.status().reasonPhrase();
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/OnLastHttpContentCallback.java b/client/src/main/java/org/asynchttpclient/netty/OnLastHttpContentCallback.java
index 4e9dd0f7a8..53e73f9eaa 100644
--- a/client/src/main/java/org/asynchttpclient/netty/OnLastHttpContentCallback.java
+++ b/client/src/main/java/org/asynchttpclient/netty/OnLastHttpContentCallback.java
@@ -20,7 +20,7 @@ protected OnLastHttpContentCallback(NettyResponseFuture> future) {
this.future = future;
}
- abstract public void call() throws Exception;
+ public abstract void call() throws Exception;
public NettyResponseFuture> future() {
return future;
diff --git a/client/src/main/java/org/asynchttpclient/netty/channel/ChannelManager.java b/client/src/main/java/org/asynchttpclient/netty/channel/ChannelManager.java
index b53b3e6f91..c5a5dce26c 100755
--- a/client/src/main/java/org/asynchttpclient/netty/channel/ChannelManager.java
+++ b/client/src/main/java/org/asynchttpclient/netty/channel/ChannelManager.java
@@ -15,7 +15,14 @@
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBufAllocator;
-import io.netty.channel.*;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFactory;
+import io.netty.channel.ChannelHandler;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.ChannelPipeline;
+import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelGroupFuture;
@@ -37,7 +44,11 @@
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.resolver.NameResolver;
import io.netty.util.Timer;
-import io.netty.util.concurrent.*;
+import io.netty.util.concurrent.DefaultThreadFactory;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GlobalEventExecutor;
+import io.netty.util.concurrent.ImmediateEventExecutor;
+import io.netty.util.concurrent.Promise;
import io.netty.util.internal.PlatformDependent;
import org.asynchttpclient.AsyncHandler;
import org.asynchttpclient.AsyncHttpClientConfig;
@@ -100,14 +111,13 @@ public class ChannelManager {
private AsyncHttpClientHandler wsHandler;
public ChannelManager(final AsyncHttpClientConfig config, Timer nettyTimer) {
-
this.config = config;
- this.sslEngineFactory = config.getSslEngineFactory() != null ? config.getSslEngineFactory() : new DefaultSslEngineFactory();
+ sslEngineFactory = config.getSslEngineFactory() != null ? config.getSslEngineFactory() : new DefaultSslEngineFactory();
try {
- this.sslEngineFactory.init(config);
+ sslEngineFactory.init(config);
} catch (SSLException e) {
- throw new RuntimeException("Could not initialize sslEngineFactory", e);
+ throw new RuntimeException("Could not initialize SslEngineFactory", e);
}
ChannelPool channelPool = config.getChannelPool();
@@ -118,16 +128,16 @@ public ChannelManager(final AsyncHttpClientConfig config, Timer nettyTimer) {
channelPool = NoopChannelPool.INSTANCE;
}
}
- this.channelPool = channelPool;
+ this.channelPool = channelPool;
openChannels = new DefaultChannelGroup("asyncHttpClient", GlobalEventExecutor.INSTANCE);
-
handshakeTimeout = config.getHandshakeTimeout();
// check if external EventLoopGroup is defined
ThreadFactory threadFactory = config.getThreadFactory() != null ? config.getThreadFactory() : new DefaultThreadFactory(config.getThreadPoolName());
allowReleaseEventLoopGroup = config.getEventLoopGroup() == null;
TransportFactory extends Channel, ? extends EventLoopGroup> transportFactory;
+
if (allowReleaseEventLoopGroup) {
if (config.isUseNativeTransport()) {
transportFactory = getNativeTransportFactory();
@@ -161,8 +171,7 @@ public static boolean isSslHandlerConfigured(ChannelPipeline pipeline) {
return pipeline.get(SSL_HANDLER) != null;
}
- private Bootstrap newBootstrap(ChannelFactory extends Channel> channelFactory, EventLoopGroup eventLoopGroup, AsyncHttpClientConfig config) {
- @SuppressWarnings("deprecation")
+ private static Bootstrap newBootstrap(ChannelFactory extends Channel> channelFactory, EventLoopGroup eventLoopGroup, AsyncHttpClientConfig config) {
Bootstrap bootstrap = new Bootstrap().channelFactory(channelFactory).group(eventLoopGroup)
.option(ChannelOption.ALLOCATOR, config.getAllocator() != null ? config.getAllocator() : ByteBufAllocator.DEFAULT)
.option(ChannelOption.TCP_NODELAY, config.isTcpNoDelay())
@@ -193,8 +202,7 @@ private Bootstrap newBootstrap(ChannelFactory extends Channel> channelFactory,
return bootstrap;
}
- @SuppressWarnings("unchecked")
- private TransportFactory extends Channel, ? extends EventLoopGroup> getNativeTransportFactory() {
+ private static TransportFactory extends Channel, ? extends EventLoopGroup> getNativeTransportFactory() {
String nativeTransportFactoryClassName = null;
if (PlatformDependent.isOsx()) {
nativeTransportFactoryClassName = "org.asynchttpclient.netty.channel.KQueueTransportFactory";
@@ -206,18 +214,16 @@ private Bootstrap newBootstrap(ChannelFactory extends Channel> channelFactory,
if (nativeTransportFactoryClassName != null) {
return (TransportFactory extends Channel, ? extends EventLoopGroup>) Class.forName(nativeTransportFactoryClassName).newInstance();
}
- } catch (Exception e) {
+ } catch (Exception ignored) {
+ // Ignore
}
throw new IllegalArgumentException("No suitable native transport (epoll or kqueue) available");
}
public void configureBootstraps(NettyRequestSender requestSender) {
-
final AsyncHttpClientHandler httpHandler = new HttpHandler(config, this, requestSender);
wsHandler = new WebSocketHandler(config, this, requestSender);
- final LoggingHandler loggingHandler = new LoggingHandler(LogLevel.TRACE);
-
httpBootstrap.handler(new ChannelInitializer() {
@Override
protected void initChannel(Channel ch) {
@@ -228,11 +234,12 @@ protected void initChannel(Channel ch) {
.addLast(AHC_HTTP_HANDLER, httpHandler);
if (LOGGER.isTraceEnabled()) {
- pipeline.addFirst(LOGGING_HANDLER, loggingHandler);
+ pipeline.addFirst(LOGGING_HANDLER, new LoggingHandler(LogLevel.TRACE));
}
- if (config.getHttpAdditionalChannelInitializer() != null)
+ if (config.getHttpAdditionalChannelInitializer() != null) {
config.getHttpAdditionalChannelInitializer().accept(ch);
+ }
}
});
@@ -247,26 +254,28 @@ protected void initChannel(Channel ch) {
pipeline.addBefore(AHC_WS_HANDLER, WS_COMPRESSOR_HANDLER, WebSocketClientCompressionHandler.INSTANCE);
}
- if (LOGGER.isDebugEnabled()) {
- pipeline.addFirst(LOGGING_HANDLER, loggingHandler);
+ if (LOGGER.isTraceEnabled()) {
+ pipeline.addFirst(LOGGING_HANDLER, new LoggingHandler(LogLevel.TRACE));
}
- if (config.getWsAdditionalChannelInitializer() != null)
+ if (config.getWsAdditionalChannelInitializer() != null) {
config.getWsAdditionalChannelInitializer().accept(ch);
+ }
}
});
}
private HttpContentDecompressor newHttpContentDecompressor() {
- if (config.isKeepEncodingHeader())
+ if (config.isKeepEncodingHeader()) {
return new HttpContentDecompressor() {
@Override
protected String getTargetContentEncoding(String contentEncoding) {
return contentEncoding;
}
};
- else
+ } else {
return new HttpContentDecompressor();
+ }
}
public final void tryToOfferChannelToPool(Channel channel, AsyncHandler> asyncHandler, boolean keepAlive, Object partitionKey) {
@@ -339,17 +348,18 @@ private HttpClientCodec newHttpClientCodec() {
private SslHandler createSslHandler(String peerHost, int peerPort) {
SSLEngine sslEngine = sslEngineFactory.newSslEngine(config, peerHost, peerPort);
SslHandler sslHandler = new SslHandler(sslEngine);
- if (handshakeTimeout > 0)
+ if (handshakeTimeout > 0) {
sslHandler.setHandshakeTimeoutMillis(handshakeTimeout);
+ }
return sslHandler;
}
public Future updatePipelineForHttpTunneling(ChannelPipeline pipeline, Uri requestUri) {
-
Future whenHandshaked = null;
- if (pipeline.get(HTTP_CLIENT_CODEC) != null)
+ if (pipeline.get(HTTP_CLIENT_CODEC) != null) {
pipeline.remove(HTTP_CLIENT_CODEC);
+ }
if (requestUri.isSecured()) {
if (!isSslHandlerConfigured(pipeline)) {
@@ -404,13 +414,13 @@ public SslHandler addSslHandler(ChannelPipeline pipeline, Uri uri, String virtua
}
public Future getBootstrap(Uri uri, NameResolver nameResolver, ProxyServer proxy) {
-
final Promise promise = ImmediateEventExecutor.INSTANCE.newPromise();
if (uri.isWebSocket() && proxy == null) {
return promise.setSuccess(wsBootstrap);
+ }
- } else if (proxy != null && proxy.getProxyType().isSocks()) {
+ if (proxy != null && proxy.getProxyType().isSocks()) {
Bootstrap socksBootstrap = httpBootstrap.clone();
ChannelHandler httpBootstrapHandler = socksBootstrap.config().handler();
@@ -461,17 +471,19 @@ protected void initChannel(Channel channel) throws Exception {
public void upgradePipelineForWebSockets(ChannelPipeline pipeline) {
pipeline.addAfter(HTTP_CLIENT_CODEC, WS_ENCODER_HANDLER, new WebSocket08FrameEncoder(true));
- pipeline.addAfter(WS_ENCODER_HANDLER, WS_DECODER_HANDLER, new WebSocket08FrameDecoder(false, config.isEnableWebSocketCompression(), config.getWebSocketMaxFrameSize()));
+ pipeline.addAfter(WS_ENCODER_HANDLER, WS_DECODER_HANDLER, new WebSocket08FrameDecoder(false,
+ config.isEnableWebSocketCompression(), config.getWebSocketMaxFrameSize()));
if (config.isAggregateWebSocketFrameFragments()) {
pipeline.addAfter(WS_DECODER_HANDLER, WS_FRAME_AGGREGATOR, new WebSocketFrameAggregator(config.getWebSocketMaxBufferSize()));
}
+
pipeline.remove(HTTP_CLIENT_CODEC);
}
private OnLastHttpContentCallback newDrainCallback(final NettyResponseFuture> future, final Channel channel, final boolean keepAlive, final Object partitionKey) {
-
return new OnLastHttpContentCallback(future) {
+ @Override
public void call() {
tryToOfferChannelToPool(channel, future.getAsyncHandler(), keepAlive, partitionKey);
}
@@ -495,15 +507,23 @@ public EventLoopGroup getEventLoopGroup() {
}
public ClientStats getClientStats() {
- Map totalConnectionsPerHost = openChannels.stream().map(Channel::remoteAddress).filter(a -> a instanceof InetSocketAddress)
- .map(a -> (InetSocketAddress) a).map(InetSocketAddress::getHostString).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
+ Map totalConnectionsPerHost = openChannels.stream()
+ .map(Channel::remoteAddress)
+ .filter(a -> a instanceof InetSocketAddress)
+ .map(a -> (InetSocketAddress) a)
+ .map(InetSocketAddress::getHostString)
+ .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
+
Map idleConnectionsPerHost = channelPool.getIdleChannelCountPerHost();
- Map statsPerHost = totalConnectionsPerHost.entrySet().stream().collect(Collectors.toMap(Entry::getKey, entry -> {
- final long totalConnectionCount = entry.getValue();
- final long idleConnectionCount = idleConnectionsPerHost.getOrDefault(entry.getKey(), 0L);
- final long activeConnectionCount = totalConnectionCount - idleConnectionCount;
- return new HostStats(activeConnectionCount, idleConnectionCount);
- }));
+
+ Map statsPerHost = totalConnectionsPerHost.entrySet()
+ .stream()
+ .collect(Collectors.toMap(Entry::getKey, entry -> {
+ final long totalConnectionCount = entry.getValue();
+ final long idleConnectionCount = idleConnectionsPerHost.getOrDefault(entry.getKey(), 0L);
+ final long activeConnectionCount = totalConnectionCount - idleConnectionCount;
+ return new HostStats(activeConnectionCount, idleConnectionCount);
+ }));
return new ClientStats(statsPerHost);
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/channel/ChannelState.java b/client/src/main/java/org/asynchttpclient/netty/channel/ChannelState.java
index a76df2b90d..ede914a2dd 100644
--- a/client/src/main/java/org/asynchttpclient/netty/channel/ChannelState.java
+++ b/client/src/main/java/org/asynchttpclient/netty/channel/ChannelState.java
@@ -15,4 +15,4 @@
public enum ChannelState {
NEW, POOLED, RECONNECTED, CLOSED,
-}
\ No newline at end of file
+}
diff --git a/client/src/main/java/org/asynchttpclient/netty/channel/Channels.java b/client/src/main/java/org/asynchttpclient/netty/channel/Channels.java
index 615dfaf917..8ac36f6fa4 100755
--- a/client/src/main/java/org/asynchttpclient/netty/channel/Channels.java
+++ b/client/src/main/java/org/asynchttpclient/netty/channel/Channels.java
@@ -20,13 +20,17 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class Channels {
+public final class Channels {
private static final Logger LOGGER = LoggerFactory.getLogger(Channels.class);
private static final AttributeKey