Java 1.8 upgrade
This commit is contained in:
parent
b704baf466
commit
bb04d078ad
|
@ -124,7 +124,7 @@ public class HttpCacheEntry implements MessageHeaders, Serializable {
|
|||
*/
|
||||
public HttpCacheEntry(final Date requestDate, final Date responseDate, final int status,
|
||||
final Header[] responseHeaders, final Resource resource) {
|
||||
this(requestDate, responseDate, status, responseHeaders, resource, new HashMap<String,String>());
|
||||
this(requestDate, responseDate, status, responseHeaders, resource, new HashMap<>());
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -187,7 +187,7 @@ public abstract class AbstractSerializingAsyncCacheStorage<T, CAS> implements Ht
|
|||
|
||||
@Override
|
||||
public void completed(final Boolean result) {
|
||||
if (result) {
|
||||
if (result.booleanValue()) {
|
||||
callback.completed(result);
|
||||
} else {
|
||||
if (!complexCancellable.isCancelled()) {
|
||||
|
|
|
@ -57,7 +57,6 @@ import org.apache.hc.core5.annotation.ThreadingBehavior;
|
|||
import org.apache.hc.core5.concurrent.CancellableDependency;
|
||||
import org.apache.hc.core5.concurrent.ComplexFuture;
|
||||
import org.apache.hc.core5.concurrent.FutureCallback;
|
||||
import org.apache.hc.core5.function.Factory;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.EntityDetails;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
|
@ -102,14 +101,8 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
|
|||
super(config);
|
||||
this.responseCache = Args.notNull(cache, "Response cache");
|
||||
this.cacheRevalidator = cacheRevalidator;
|
||||
this.conditionalRequestBuilder = new ConditionalRequestBuilder<>(new Factory<HttpRequest, HttpRequest>() {
|
||||
|
||||
@Override
|
||||
public HttpRequest create(final HttpRequest request) {
|
||||
return BasicRequestBuilder.copy(request).build();
|
||||
}
|
||||
|
||||
});
|
||||
this.conditionalRequestBuilder = new ConditionalRequestBuilder<>(request ->
|
||||
BasicRequestBuilder.copy(request).build());
|
||||
}
|
||||
|
||||
AsyncCachingExec(
|
||||
|
@ -675,14 +668,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
|
|||
cacheRevalidator.revalidateCacheEntry(
|
||||
responseCache.generateKey(target, request, entry),
|
||||
asyncExecCallback,
|
||||
new DefaultAsyncCacheRevalidator.RevalidationCall() {
|
||||
|
||||
@Override
|
||||
public void execute(final AsyncExecCallback asyncExecCallback) {
|
||||
revalidateCacheEntry(target, request, entityProducer, fork, chain, asyncExecCallback, entry);
|
||||
}
|
||||
|
||||
});
|
||||
asyncExecCallback1 -> revalidateCacheEntry(target, request, entityProducer, fork, chain, asyncExecCallback1, entry));
|
||||
triggerResponse(cacheResponse, scope, asyncExecCallback);
|
||||
} catch (final ResourceIOException ex) {
|
||||
asyncExecCallback.failed(ex);
|
||||
|
@ -771,26 +757,12 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
|
|||
recordCacheUpdate(scope.clientContext);
|
||||
}
|
||||
if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
|
||||
return new AsyncExecCallbackWrapper(asyncExecCallback, new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
triggerUpdatedCacheEntryResponse(backendResponse, responseDate);
|
||||
}
|
||||
|
||||
});
|
||||
return new AsyncExecCallbackWrapper(asyncExecCallback, () -> triggerUpdatedCacheEntryResponse(backendResponse, responseDate));
|
||||
}
|
||||
if (staleIfErrorAppliesTo(statusCode)
|
||||
&& !staleResponseNotAllowed(request, cacheEntry, getCurrentDate())
|
||||
&& validityPolicy.mayReturnStaleIfError(request, cacheEntry, responseDate)) {
|
||||
return new AsyncExecCallbackWrapper(asyncExecCallback, new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
triggerResponseStaleCacheEntry();
|
||||
}
|
||||
|
||||
});
|
||||
return new AsyncExecCallbackWrapper(asyncExecCallback, this::triggerResponseStaleCacheEntry);
|
||||
}
|
||||
return new BackendResponseHandler(target, conditionalRequest, requestDate, responseDate, scope, asyncExecCallback);
|
||||
}
|
||||
|
@ -809,20 +781,16 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
|
|||
final HttpRequest unconditional = conditionalRequestBuilder.buildUnconditionalRequest(
|
||||
BasicRequestBuilder.copy(scope.originalRequest).build());
|
||||
|
||||
callback1 = new AsyncExecCallbackWrapper(asyncExecCallback, new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
chainProceed(unconditional, entityProducer, scope, chain, new AsyncExecCallback() {
|
||||
callback1 = new AsyncExecCallbackWrapper(asyncExecCallback, () -> chainProceed(unconditional, entityProducer, scope, chain, new AsyncExecCallback() {
|
||||
|
||||
@Override
|
||||
public AsyncDataConsumer handleResponse(
|
||||
final HttpResponse backendResponse2,
|
||||
final EntityDetails entityDetails) throws HttpException, IOException {
|
||||
final EntityDetails entityDetails1) throws HttpException, IOException {
|
||||
final Date responseDate2 = getCurrentDate();
|
||||
final AsyncExecCallback callback2 = evaluateResponse(backendResponse2, responseDate2);
|
||||
callbackRef.set(callback2);
|
||||
return callback2.handleResponse(backendResponse2, entityDetails);
|
||||
return callback2.handleResponse(backendResponse2, entityDetails1);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -855,11 +823,7 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
|
|||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
}));
|
||||
} else {
|
||||
callback1 = evaluateResponse(backendResponse1, responseDate1);
|
||||
}
|
||||
|
@ -1036,49 +1000,21 @@ class AsyncCachingExec extends CachingExecBase implements AsyncExecChainHandler
|
|||
final Header resultEtagHeader = backendResponse.getFirstHeader(HeaderConstants.ETAG);
|
||||
if (resultEtagHeader == null) {
|
||||
LOG.warn("304 response did not contain ETag");
|
||||
callback = new AsyncExecCallbackWrapper(asyncExecCallback, new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
callBackend(target, request, entityProducer, scope, chain, asyncExecCallback);
|
||||
}
|
||||
|
||||
});
|
||||
callback = new AsyncExecCallbackWrapper(asyncExecCallback, () -> callBackend(target, request, entityProducer, scope, chain, asyncExecCallback));
|
||||
} else {
|
||||
final String resultEtag = resultEtagHeader.getValue();
|
||||
final Variant matchingVariant = variants.get(resultEtag);
|
||||
if (matchingVariant == null) {
|
||||
LOG.debug("304 response did not contain ETag matching one sent in If-None-Match");
|
||||
callback = new AsyncExecCallbackWrapper(asyncExecCallback, new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
callBackend(target, request, entityProducer, scope, chain, asyncExecCallback);
|
||||
}
|
||||
|
||||
});
|
||||
callback = new AsyncExecCallbackWrapper(asyncExecCallback, () -> callBackend(target, request, entityProducer, scope, chain, asyncExecCallback));
|
||||
} else {
|
||||
if (revalidationResponseIsTooOld(backendResponse, matchingVariant.getEntry())) {
|
||||
final HttpRequest unconditional = conditionalRequestBuilder.buildUnconditionalRequest(
|
||||
BasicRequestBuilder.copy(request).build());
|
||||
scope.clientContext.setAttribute(HttpCoreContext.HTTP_REQUEST, unconditional);
|
||||
callback = new AsyncExecCallbackWrapper(asyncExecCallback, new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
callBackend(target, request, entityProducer, scope, chain, asyncExecCallback);
|
||||
}
|
||||
|
||||
});
|
||||
callback = new AsyncExecCallbackWrapper(asyncExecCallback, () -> callBackend(target, request, entityProducer, scope, chain, asyncExecCallback));
|
||||
} else {
|
||||
callback = new AsyncExecCallbackWrapper(asyncExecCallback, new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
updateVariantCacheEntry(backendResponse, responseDate, matchingVariant);
|
||||
}
|
||||
|
||||
});
|
||||
callback = new AsyncExecCallbackWrapper(asyncExecCallback, () -> updateVariantCacheEntry(backendResponse, responseDate, matchingVariant));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -34,7 +34,6 @@ import java.util.Set;
|
|||
import org.apache.hc.client5.http.cache.HeaderConstants;
|
||||
import org.apache.hc.client5.http.cache.HttpAsyncCacheInvalidator;
|
||||
import org.apache.hc.client5.http.cache.HttpAsyncCacheStorage;
|
||||
import org.apache.hc.client5.http.cache.HttpCacheCASOperation;
|
||||
import org.apache.hc.client5.http.cache.HttpCacheEntry;
|
||||
import org.apache.hc.client5.http.cache.HttpCacheUpdateException;
|
||||
import org.apache.hc.client5.http.cache.ResourceFactory;
|
||||
|
@ -211,14 +210,7 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
|
|||
@Override
|
||||
public void completed(final Boolean result) {
|
||||
storage.updateEntry(cacheKey,
|
||||
new HttpCacheCASOperation() {
|
||||
|
||||
@Override
|
||||
public HttpCacheEntry execute(final HttpCacheEntry existing) throws ResourceIOException {
|
||||
return cacheUpdateHandler.updateParentCacheEntry(req.getRequestUri(), existing, entry, variantKey, variantCacheKey);
|
||||
}
|
||||
|
||||
},
|
||||
existing -> cacheUpdateHandler.updateParentCacheEntry(req.getRequestUri(), existing, entry, variantKey, variantCacheKey),
|
||||
new FutureCallback<Boolean>() {
|
||||
|
||||
@Override
|
||||
|
@ -280,14 +272,7 @@ class BasicHttpAsyncCache implements HttpAsyncCache {
|
|||
final String variantKey = cacheKeyGenerator.generateVariantKey(request, entry);
|
||||
final String variantCacheKey = variant.getCacheKey();
|
||||
return storage.updateEntry(cacheKey,
|
||||
new HttpCacheCASOperation() {
|
||||
|
||||
@Override
|
||||
public HttpCacheEntry execute(final HttpCacheEntry existing) throws ResourceIOException {
|
||||
return cacheUpdateHandler.updateParentCacheEntry(request.getRequestUri(), existing, entry, variantKey, variantCacheKey);
|
||||
}
|
||||
|
||||
},
|
||||
existing -> cacheUpdateHandler.updateParentCacheEntry(request.getRequestUri(), existing, entry, variantKey, variantCacheKey),
|
||||
new FutureCallback<Boolean>() {
|
||||
|
||||
@Override
|
||||
|
|
|
@ -31,7 +31,6 @@ import java.util.HashMap;
|
|||
import java.util.Map;
|
||||
|
||||
import org.apache.hc.client5.http.cache.HeaderConstants;
|
||||
import org.apache.hc.client5.http.cache.HttpCacheCASOperation;
|
||||
import org.apache.hc.client5.http.cache.HttpCacheEntry;
|
||||
import org.apache.hc.client5.http.cache.HttpCacheInvalidator;
|
||||
import org.apache.hc.client5.http.cache.HttpCacheStorage;
|
||||
|
@ -163,14 +162,7 @@ class BasicHttpCache implements HttpCache {
|
|||
final String variantCacheKey = cacheKeyGenerator.generateKey(host, req, entry);
|
||||
storeEntry(variantCacheKey, entry);
|
||||
try {
|
||||
storage.updateEntry(cacheKey, new HttpCacheCASOperation() {
|
||||
|
||||
@Override
|
||||
public HttpCacheEntry execute(final HttpCacheEntry existing) throws ResourceIOException {
|
||||
return cacheUpdateHandler.updateParentCacheEntry(req.getRequestUri(), existing, entry, variantKey, variantCacheKey);
|
||||
}
|
||||
|
||||
});
|
||||
storage.updateEntry(cacheKey, existing -> cacheUpdateHandler.updateParentCacheEntry(req.getRequestUri(), existing, entry, variantKey, variantCacheKey));
|
||||
} catch (final HttpCacheUpdateException ex) {
|
||||
if (LOG.isWarnEnabled()) {
|
||||
LOG.warn("Cannot update cache entry with key {}", cacheKey);
|
||||
|
@ -194,14 +186,7 @@ class BasicHttpCache implements HttpCache {
|
|||
final String variantCacheKey = variant.getCacheKey();
|
||||
|
||||
try {
|
||||
storage.updateEntry(cacheKey, new HttpCacheCASOperation() {
|
||||
|
||||
@Override
|
||||
public HttpCacheEntry execute(final HttpCacheEntry existing) throws ResourceIOException {
|
||||
return cacheUpdateHandler.updateParentCacheEntry(request.getRequestUri(), existing, entry, variantKey, variantCacheKey);
|
||||
}
|
||||
|
||||
});
|
||||
storage.updateEntry(cacheKey, existing -> cacheUpdateHandler.updateParentCacheEntry(request.getRequestUri(), existing, entry, variantKey, variantCacheKey));
|
||||
} catch (final HttpCacheUpdateException ex) {
|
||||
if (LOG.isWarnEnabled()) {
|
||||
LOG.warn("Cannot update cache entry with key {}", cacheKey);
|
||||
|
|
|
@ -66,7 +66,7 @@ class BasicIdGenerator {
|
|||
buffer.append(System.currentTimeMillis());
|
||||
buffer.append('.');
|
||||
final Formatter formatter = new Formatter(buffer, Locale.ROOT);
|
||||
formatter.format("%1$016x-%2$08x", Long.valueOf(this.count), Integer.valueOf(rndnum));
|
||||
formatter.format("%1$016x-%2$08x", this.count, rndnum);
|
||||
formatter.close();
|
||||
buffer.append('.');
|
||||
buffer.append(this.hostname);
|
||||
|
|
|
@ -48,7 +48,6 @@ import org.apache.hc.client5.http.impl.ExecSupport;
|
|||
import org.apache.hc.client5.http.protocol.HttpClientContext;
|
||||
import org.apache.hc.client5.http.schedule.SchedulingStrategy;
|
||||
import org.apache.hc.client5.http.utils.DateUtils;
|
||||
import org.apache.hc.core5.function.Factory;
|
||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
|
@ -112,14 +111,8 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
|
|||
super(config);
|
||||
this.responseCache = Args.notNull(cache, "Response cache");
|
||||
this.cacheRevalidator = cacheRevalidator;
|
||||
this.conditionalRequestBuilder = new ConditionalRequestBuilder<>(new Factory<ClassicHttpRequest, ClassicHttpRequest>() {
|
||||
|
||||
@Override
|
||||
public ClassicHttpRequest create(final ClassicHttpRequest classicHttpRequest) {
|
||||
return ClassicRequestBuilder.copy(classicHttpRequest).build();
|
||||
}
|
||||
|
||||
});
|
||||
this.conditionalRequestBuilder = new ConditionalRequestBuilder<>(classicHttpRequest ->
|
||||
ClassicRequestBuilder.copy(classicHttpRequest).build());
|
||||
}
|
||||
|
||||
CachingExec(
|
||||
|
@ -294,14 +287,7 @@ class CachingExec extends CachingExecBase implements ExecChainHandler {
|
|||
final SimpleHttpResponse response = generateCachedResponse(request, context, entry, now);
|
||||
cacheRevalidator.revalidateCacheEntry(
|
||||
responseCache.generateKey(target, request, entry),
|
||||
new DefaultCacheRevalidator.RevalidationCall() {
|
||||
|
||||
@Override
|
||||
public ClassicHttpResponse execute() throws HttpException, IOException {
|
||||
return revalidateCacheEntry(target, request, fork, chain, entry);
|
||||
}
|
||||
|
||||
});
|
||||
() -> revalidateCacheEntry(target, request, fork, chain, entry));
|
||||
return convert(response, scope);
|
||||
}
|
||||
return revalidateCacheEntry(target, request, scope, chain, entry);
|
||||
|
|
|
@ -26,9 +26,7 @@
|
|||
*/
|
||||
package org.apache.hc.client5.http.impl.cache;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
|
||||
|
@ -130,14 +128,7 @@ public class CachingH2AsyncClientBuilder extends H2AsyncClientBuilder {
|
|||
} else {
|
||||
final ManagedHttpCacheStorage managedStorage = new ManagedHttpCacheStorage(config);
|
||||
if (this.deleteCache) {
|
||||
addCloseable(new Closeable() {
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
managedStorage.shutdown();
|
||||
}
|
||||
|
||||
});
|
||||
addCloseable(managedStorage::shutdown);
|
||||
} else {
|
||||
addCloseable(managedStorage);
|
||||
}
|
||||
|
@ -153,14 +144,7 @@ public class CachingH2AsyncClientBuilder extends H2AsyncClientBuilder {
|
|||
DefaultAsyncCacheRevalidator cacheRevalidator = null;
|
||||
if (config.getAsynchronousWorkers() > 0) {
|
||||
final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(config.getAsynchronousWorkers());
|
||||
addCloseable(new Closeable() {
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
|
||||
});
|
||||
addCloseable(executorService::shutdownNow);
|
||||
cacheRevalidator = new DefaultAsyncCacheRevalidator(
|
||||
executorService,
|
||||
this.schedulingStrategy != null ? this.schedulingStrategy : ImmediateSchedulingStrategy.INSTANCE);
|
||||
|
|
|
@ -26,9 +26,7 @@
|
|||
*/
|
||||
package org.apache.hc.client5.http.impl.cache;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
|
||||
|
@ -130,14 +128,7 @@ public class CachingHttpAsyncClientBuilder extends HttpAsyncClientBuilder {
|
|||
} else {
|
||||
final ManagedHttpCacheStorage managedStorage = new ManagedHttpCacheStorage(config);
|
||||
if (this.deleteCache) {
|
||||
addCloseable(new Closeable() {
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
managedStorage.shutdown();
|
||||
}
|
||||
|
||||
});
|
||||
addCloseable(managedStorage::shutdown);
|
||||
} else {
|
||||
addCloseable(managedStorage);
|
||||
}
|
||||
|
@ -153,14 +144,7 @@ public class CachingHttpAsyncClientBuilder extends HttpAsyncClientBuilder {
|
|||
DefaultAsyncCacheRevalidator cacheRevalidator = null;
|
||||
if (config.getAsynchronousWorkers() > 0) {
|
||||
final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(config.getAsynchronousWorkers());
|
||||
addCloseable(new Closeable() {
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
|
||||
});
|
||||
addCloseable(executorService::shutdownNow);
|
||||
cacheRevalidator = new DefaultAsyncCacheRevalidator(
|
||||
executorService,
|
||||
this.schedulingStrategy != null ? this.schedulingStrategy : ImmediateSchedulingStrategy.INSTANCE);
|
||||
|
|
|
@ -26,9 +26,7 @@
|
|||
*/
|
||||
package org.apache.hc.client5.http.impl.cache;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
|
||||
|
@ -122,14 +120,7 @@ public class CachingHttpClientBuilder extends HttpClientBuilder {
|
|||
} else {
|
||||
final ManagedHttpCacheStorage managedStorage = new ManagedHttpCacheStorage(config);
|
||||
if (this.deleteCache) {
|
||||
addCloseable(new Closeable() {
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
managedStorage.shutdown();
|
||||
}
|
||||
|
||||
});
|
||||
addCloseable(managedStorage::shutdown);
|
||||
} else {
|
||||
addCloseable(managedStorage);
|
||||
}
|
||||
|
@ -145,14 +136,7 @@ public class CachingHttpClientBuilder extends HttpClientBuilder {
|
|||
DefaultCacheRevalidator cacheRevalidator = null;
|
||||
if (config.getAsynchronousWorkers() > 0) {
|
||||
final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(config.getAsynchronousWorkers());
|
||||
addCloseable(new Closeable() {
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
|
||||
});
|
||||
addCloseable(executorService::shutdownNow);
|
||||
cacheRevalidator = new DefaultCacheRevalidator(
|
||||
executorService,
|
||||
this.schedulingStrategy != null ? this.schedulingStrategy : ImmediateSchedulingStrategy.INSTANCE);
|
||||
|
|
|
@ -70,7 +70,7 @@ public class DefaultAsyncCacheInvalidator extends CacheInvalidatorBase implement
|
|||
@Override
|
||||
public void completed(final Boolean result) {
|
||||
if (LOG.isDebugEnabled()) {
|
||||
if (result) {
|
||||
if (result.booleanValue()) {
|
||||
LOG.debug("Cache entry with key {} successfully flushed", cacheKey);
|
||||
} else {
|
||||
LOG.debug("Cache entry with key {} could not be flushed", cacheKey);
|
||||
|
|
|
@ -118,11 +118,7 @@ class DefaultAsyncCacheRevalidator extends CacheRevalidatorBase {
|
|||
final String cacheKey ,
|
||||
final AsyncExecCallback asyncExecCallback,
|
||||
final RevalidationCall call) {
|
||||
scheduleRevalidation(cacheKey, new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
call.execute(new AsyncExecCallback() {
|
||||
scheduleRevalidation(cacheKey, () -> call.execute(new AsyncExecCallback() {
|
||||
|
||||
private final AtomicReference<HttpResponse> responseRef = new AtomicReference<>(null);
|
||||
|
||||
|
@ -167,10 +163,7 @@ class DefaultAsyncCacheRevalidator extends CacheRevalidatorBase {
|
|||
}
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -75,10 +75,7 @@ class DefaultCacheRevalidator extends CacheRevalidatorBase {
|
|||
public void revalidateCacheEntry(
|
||||
final String cacheKey,
|
||||
final RevalidationCall call) {
|
||||
scheduleRevalidation(cacheKey, new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
scheduleRevalidation(cacheKey, () -> {
|
||||
try (ClassicHttpResponse httpResponse = call.execute()) {
|
||||
if (httpResponse.getCode() < HttpStatus.SC_SERVER_ERROR && !isStale(httpResponse)) {
|
||||
jobSuccessful(cacheKey);
|
||||
|
@ -96,8 +93,6 @@ class DefaultCacheRevalidator extends CacheRevalidatorBase {
|
|||
LOG.error("Unexpected runtime exception thrown during asynchronous revalidation", ex);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -358,10 +358,10 @@ class WarningValue {
|
|||
@Override
|
||||
public String toString() {
|
||||
if (warnDate != null) {
|
||||
return String.format("%d %s %s \"%s\"", Integer.valueOf(warnCode),
|
||||
return String.format("%d %s %s \"%s\"", warnCode,
|
||||
warnAgent, warnText, DateUtils.formatDate(warnDate));
|
||||
} else {
|
||||
return String.format("%d %s %s", Integer.valueOf(warnCode), warnAgent, warnText);
|
||||
return String.format("%d %s %s", warnCode, warnAgent, warnText);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -47,11 +47,7 @@ import net.spy.memcached.CASResponse;
|
|||
import net.spy.memcached.CASValue;
|
||||
import net.spy.memcached.MemcachedClient;
|
||||
import net.spy.memcached.internal.BulkFuture;
|
||||
import net.spy.memcached.internal.BulkGetCompletionListener;
|
||||
import net.spy.memcached.internal.BulkGetFuture;
|
||||
import net.spy.memcached.internal.GetCompletionListener;
|
||||
import net.spy.memcached.internal.GetFuture;
|
||||
import net.spy.memcached.internal.OperationCompletionListener;
|
||||
import net.spy.memcached.internal.OperationFuture;
|
||||
|
||||
/**
|
||||
|
@ -160,10 +156,7 @@ public class MemcachedHttpAsyncCacheStorage extends AbstractBinaryAsyncCacheStor
|
|||
}
|
||||
|
||||
private <T> Cancellable operation(final OperationFuture<T> operationFuture, final FutureCallback<T> callback) {
|
||||
operationFuture.addListener(new OperationCompletionListener() {
|
||||
|
||||
@Override
|
||||
public void onComplete(final OperationFuture<?> future) throws Exception {
|
||||
operationFuture.addListener(future -> {
|
||||
try {
|
||||
callback.completed(operationFuture.get());
|
||||
} catch (final ExecutionException ex) {
|
||||
|
@ -173,8 +166,6 @@ public class MemcachedHttpAsyncCacheStorage extends AbstractBinaryAsyncCacheStor
|
|||
callback.failed(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
return Operations.cancellable(operationFuture);
|
||||
}
|
||||
|
@ -187,10 +178,7 @@ public class MemcachedHttpAsyncCacheStorage extends AbstractBinaryAsyncCacheStor
|
|||
@Override
|
||||
protected Cancellable restore(final String storageKey, final FutureCallback<byte[]> callback) {
|
||||
final GetFuture<Object> getFuture = client.asyncGet(storageKey);
|
||||
getFuture.addListener(new GetCompletionListener() {
|
||||
|
||||
@Override
|
||||
public void onComplete(final GetFuture<?> future) throws Exception {
|
||||
getFuture.addListener(future -> {
|
||||
try {
|
||||
callback.completed(castAsByteArray(getFuture.get()));
|
||||
} catch (final ExecutionException ex) {
|
||||
|
@ -200,8 +188,6 @@ public class MemcachedHttpAsyncCacheStorage extends AbstractBinaryAsyncCacheStor
|
|||
callback.failed(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
return Operations.cancellable(getFuture);
|
||||
}
|
||||
|
@ -242,17 +228,13 @@ public class MemcachedHttpAsyncCacheStorage extends AbstractBinaryAsyncCacheStor
|
|||
@Override
|
||||
protected Cancellable bulkRestore(final Collection<String> storageKeys, final FutureCallback<Map<String, byte[]>> callback) {
|
||||
final BulkFuture<Map<String, Object>> future = client.asyncGetBulk(storageKeys);
|
||||
future.addListener(new BulkGetCompletionListener() {
|
||||
|
||||
@Override
|
||||
public void onComplete(final BulkGetFuture<?> future) throws Exception {
|
||||
final Map<String, ?> storageObjectMap = future.get();
|
||||
future.addListener(future1 -> {
|
||||
final Map<String, ?> storageObjectMap = future1.get();
|
||||
final Map<String, byte[]> resultMap = new HashMap<>(storageObjectMap.size());
|
||||
for (final Map.Entry<String, ?> resultEntry: storageObjectMap.entrySet()) {
|
||||
resultMap.put(resultEntry.getKey(), castAsByteArray(resultEntry.getValue()));
|
||||
}
|
||||
callback.completed(resultMap);
|
||||
}
|
||||
});
|
||||
return Operations.cancellable(future);
|
||||
}
|
||||
|
|
|
@ -217,7 +217,7 @@ public class TestHttpCacheEntry {
|
|||
public void canProvideVariantMap() {
|
||||
new HttpCacheEntry(new Date(), new Date(), HttpStatus.SC_OK,
|
||||
new Header[]{}, mockResource,
|
||||
new HashMap<String,String>());
|
||||
new HashMap<>());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -155,7 +155,7 @@ public abstract class AbstractProtocolTest {
|
|||
EasyMock.expect(mockCache.getCacheEntry(EasyMock.isA(HttpHost.class), EasyMock.isA(HttpRequest.class)))
|
||||
.andReturn(null).anyTimes();
|
||||
EasyMock.expect(mockCache.getVariantCacheEntriesWithEtags(EasyMock.isA(HttpHost.class), EasyMock.isA(HttpRequest.class)))
|
||||
.andReturn(new HashMap<String,Variant>()).anyTimes();
|
||||
.andReturn(new HashMap<>()).anyTimes();
|
||||
|
||||
mockCache.flushCacheEntriesFor(EasyMock.isA(HttpHost.class), EasyMock.isA(HttpRequest.class));
|
||||
EasyMock.expectLastCall().anyTimes();
|
||||
|
|
|
@ -35,7 +35,6 @@ import java.util.HashMap;
|
|||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.apache.hc.client5.http.cache.HttpCacheCASOperation;
|
||||
import org.apache.hc.client5.http.cache.HttpCacheEntry;
|
||||
import org.apache.hc.client5.http.cache.HttpCacheStorageEntry;
|
||||
import org.apache.hc.client5.http.cache.HttpCacheUpdateException;
|
||||
|
@ -52,7 +51,6 @@ import org.mockito.ArgumentCaptor;
|
|||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
|
@ -90,15 +88,10 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
Mockito.when(impl.store(
|
||||
ArgumentMatchers.eq("bar"),
|
||||
ArgumentMatchers.<byte[]>any(),
|
||||
ArgumentMatchers.<FutureCallback<Boolean>>any())).thenAnswer(new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
ArgumentMatchers.<FutureCallback<Boolean>>any())).thenAnswer((Answer<Cancellable>) invocation -> {
|
||||
final FutureCallback<Boolean> callback = invocation.getArgument(2);
|
||||
callback.completed(true);
|
||||
return cancellable;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
impl.putEntry(key, value, operationCallback);
|
||||
|
@ -114,15 +107,10 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
final String key = "foo";
|
||||
|
||||
Mockito.when(impl.digestToStorageKey(key)).thenReturn("bar");
|
||||
Mockito.when(impl.restore(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<byte[]>>any())).thenAnswer(new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
Mockito.when(impl.restore(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<byte[]>>any())).thenAnswer((Answer<Cancellable>) invocation -> {
|
||||
final FutureCallback<byte[]> callback = invocation.getArgument(1);
|
||||
callback.completed(null);
|
||||
return cancellable;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
impl.getEntry(key, cacheEntryCallback);
|
||||
|
@ -138,15 +126,10 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
final HttpCacheEntry value = HttpTestUtils.makeCacheEntry();
|
||||
|
||||
Mockito.when(impl.digestToStorageKey(key)).thenReturn("bar");
|
||||
Mockito.when(impl.restore(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<byte[]>>any())).thenAnswer(new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
Mockito.when(impl.restore(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<byte[]>>any())).thenAnswer((Answer<Cancellable>) invocation -> {
|
||||
final FutureCallback<byte[]> callback = invocation.getArgument(1);
|
||||
callback.completed(serialize(key, value));
|
||||
return cancellable;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
impl.getEntry(key, cacheEntryCallback);
|
||||
|
@ -162,15 +145,10 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
final String key = "foo";
|
||||
final HttpCacheEntry value = HttpTestUtils.makeCacheEntry();
|
||||
Mockito.when(impl.digestToStorageKey(key)).thenReturn("bar");
|
||||
Mockito.when(impl.restore(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<byte[]>>any())).thenAnswer(new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
Mockito.when(impl.restore(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<byte[]>>any())).thenAnswer((Answer<Cancellable>) invocation -> {
|
||||
final FutureCallback<byte[]> callback = invocation.getArgument(1);
|
||||
callback.completed(serialize("not-foo", value));
|
||||
return cancellable;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
impl.getEntry(key, cacheEntryCallback);
|
||||
|
@ -187,15 +165,10 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
Mockito.when(impl.digestToStorageKey(key)).thenReturn("bar");
|
||||
Mockito.when(impl.delete(
|
||||
ArgumentMatchers.eq("bar"),
|
||||
ArgumentMatchers.<FutureCallback<Boolean>>any())).thenAnswer(new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
ArgumentMatchers.<FutureCallback<Boolean>>any())).thenAnswer((Answer<Cancellable>) invocation -> {
|
||||
final FutureCallback<Boolean> callback = invocation.getArgument(1);
|
||||
callback.completed(true);
|
||||
return cancellable;
|
||||
}
|
||||
|
||||
});
|
||||
impl.removeEntry(key, operationCallback);
|
||||
|
||||
|
@ -209,38 +182,23 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
final HttpCacheEntry updatedValue = HttpTestUtils.makeCacheEntry();
|
||||
|
||||
Mockito.when(impl.digestToStorageKey(key)).thenReturn("bar");
|
||||
Mockito.when(impl.getForUpdateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<String>>any())).thenAnswer(new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
Mockito.when(impl.getForUpdateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<String>>any())).thenAnswer((Answer<Cancellable>) invocation -> {
|
||||
final FutureCallback<byte[]> callback = invocation.getArgument(1);
|
||||
callback.completed(null);
|
||||
return cancellable;
|
||||
}
|
||||
|
||||
});
|
||||
Mockito.when(impl.store(
|
||||
ArgumentMatchers.eq("bar"),
|
||||
ArgumentMatchers.<byte[]>any(),
|
||||
ArgumentMatchers.<FutureCallback<Boolean>>any())).thenAnswer(new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
ArgumentMatchers.<FutureCallback<Boolean>>any())).thenAnswer((Answer<Cancellable>) invocation -> {
|
||||
final FutureCallback<Boolean> callback = invocation.getArgument(2);
|
||||
callback.completed(true);
|
||||
return cancellable;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
impl.updateEntry(key, new HttpCacheCASOperation() {
|
||||
|
||||
@Override
|
||||
public HttpCacheEntry execute(final HttpCacheEntry existing) throws ResourceIOException {
|
||||
impl.updateEntry(key, existing -> {
|
||||
Assert.assertThat(existing, CoreMatchers.nullValue());
|
||||
return updatedValue;
|
||||
}
|
||||
|
||||
}, operationCallback);
|
||||
|
||||
Mockito.verify(impl).getForUpdateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<String>>any());
|
||||
|
@ -255,40 +213,23 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
final HttpCacheEntry updatedValue = HttpTestUtils.makeCacheEntry();
|
||||
|
||||
Mockito.when(impl.digestToStorageKey(key)).thenReturn("bar");
|
||||
Mockito.when(impl.getForUpdateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<String>>any())).thenAnswer(new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
Mockito.when(impl.getForUpdateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<String>>any())).thenAnswer((Answer<Cancellable>) invocation -> {
|
||||
final FutureCallback<String> callback = invocation.getArgument(1);
|
||||
callback.completed("stuff");
|
||||
return cancellable;
|
||||
}
|
||||
|
||||
});
|
||||
Mockito.when(impl.getStorageObject("stuff")).thenReturn(serialize(key, existingValue));
|
||||
Mockito.when(impl.updateCAS(
|
||||
ArgumentMatchers.eq("bar"),
|
||||
ArgumentMatchers.eq("stuff"),
|
||||
ArgumentMatchers.<byte[]>any(),
|
||||
ArgumentMatchers.<FutureCallback<Boolean>>any())).thenAnswer(new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
ArgumentMatchers.<FutureCallback<Boolean>>any())).thenAnswer((Answer<Cancellable>) invocation -> {
|
||||
final FutureCallback<Boolean> callback = invocation.getArgument(3);
|
||||
callback.completed(true);
|
||||
return cancellable;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
impl.updateEntry(key, new HttpCacheCASOperation() {
|
||||
|
||||
@Override
|
||||
public HttpCacheEntry execute(final HttpCacheEntry existing) throws ResourceIOException {
|
||||
return updatedValue;
|
||||
}
|
||||
|
||||
}, operationCallback);
|
||||
impl.updateEntry(key, existing -> updatedValue, operationCallback);
|
||||
|
||||
Mockito.verify(impl).getForUpdateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<String>>any());
|
||||
Mockito.verify(impl).getStorageObject("stuff");
|
||||
|
@ -304,39 +245,24 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
|
||||
Mockito.when(impl.digestToStorageKey(key)).thenReturn("bar");
|
||||
Mockito.when(impl.getForUpdateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<String>>any())).thenAnswer(
|
||||
new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
(Answer<Cancellable>) invocation -> {
|
||||
final FutureCallback<String> callback = invocation.getArgument(1);
|
||||
callback.completed("stuff");
|
||||
return cancellable;
|
||||
}
|
||||
|
||||
});
|
||||
Mockito.when(impl.getStorageObject("stuff")).thenReturn(serialize("not-foo", existingValue));
|
||||
Mockito.when(impl.store(
|
||||
ArgumentMatchers.eq("bar"),
|
||||
ArgumentMatchers.<byte[]>any(),
|
||||
ArgumentMatchers.<FutureCallback<Boolean>>any())).thenAnswer(new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
ArgumentMatchers.<FutureCallback<Boolean>>any())).thenAnswer((Answer<Cancellable>) invocation -> {
|
||||
final FutureCallback<Boolean> callback = invocation.getArgument(2);
|
||||
callback.completed(true);
|
||||
return cancellable;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
impl.updateEntry(key, new HttpCacheCASOperation() {
|
||||
|
||||
@Override
|
||||
public HttpCacheEntry execute(final HttpCacheEntry existing) throws ResourceIOException {
|
||||
impl.updateEntry(key, existing -> {
|
||||
Assert.assertThat(existing, CoreMatchers.nullValue());
|
||||
return updatedValue;
|
||||
}
|
||||
|
||||
}, operationCallback);
|
||||
|
||||
Mockito.verify(impl).getForUpdateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<String>>any());
|
||||
|
@ -355,15 +281,10 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
|
||||
Mockito.when(impl.digestToStorageKey(key)).thenReturn("bar");
|
||||
Mockito.when(impl.getForUpdateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<String>>any())).thenAnswer(
|
||||
new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
(Answer<Cancellable>) invocation -> {
|
||||
final FutureCallback<String> callback = invocation.getArgument(1);
|
||||
callback.completed("stuff");
|
||||
return cancellable;
|
||||
}
|
||||
|
||||
});
|
||||
Mockito.when(impl.getStorageObject("stuff")).thenReturn(serialize(key, existingValue));
|
||||
final AtomicInteger count = new AtomicInteger(0);
|
||||
|
@ -371,10 +292,7 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
ArgumentMatchers.eq("bar"),
|
||||
ArgumentMatchers.eq("stuff"),
|
||||
ArgumentMatchers.<byte[]>any(),
|
||||
ArgumentMatchers.<FutureCallback<Boolean>>any())).thenAnswer(new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
ArgumentMatchers.<FutureCallback<Boolean>>any())).thenAnswer((Answer<Cancellable>) invocation -> {
|
||||
final FutureCallback<Boolean> callback = invocation.getArgument(3);
|
||||
if (count.incrementAndGet() == 1) {
|
||||
callback.completed(false);
|
||||
|
@ -382,18 +300,9 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
callback.completed(true);
|
||||
}
|
||||
return cancellable;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
impl.updateEntry(key, new HttpCacheCASOperation() {
|
||||
|
||||
@Override
|
||||
public HttpCacheEntry execute(final HttpCacheEntry existing) throws ResourceIOException {
|
||||
return updatedValue;
|
||||
}
|
||||
|
||||
}, operationCallback);
|
||||
impl.updateEntry(key, existing -> updatedValue, operationCallback);
|
||||
|
||||
Mockito.verify(impl, Mockito.times(2)).getForUpdateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<String>>any());
|
||||
Mockito.verify(impl, Mockito.times(2)).getStorageObject("stuff");
|
||||
|
@ -410,15 +319,10 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
|
||||
Mockito.when(impl.digestToStorageKey(key)).thenReturn("bar");
|
||||
Mockito.when(impl.getForUpdateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<String>>any())).thenAnswer(
|
||||
new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
(Answer<Cancellable>) invocation -> {
|
||||
final FutureCallback<String> callback = invocation.getArgument(1);
|
||||
callback.completed("stuff");
|
||||
return cancellable;
|
||||
}
|
||||
|
||||
});
|
||||
Mockito.when(impl.getStorageObject("stuff")).thenReturn(serialize(key, existingValue));
|
||||
final AtomicInteger count = new AtomicInteger(0);
|
||||
|
@ -426,10 +330,7 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
ArgumentMatchers.eq("bar"),
|
||||
ArgumentMatchers.eq("stuff"),
|
||||
ArgumentMatchers.<byte[]>any(),
|
||||
ArgumentMatchers.<FutureCallback<Boolean>>any())).thenAnswer(new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
ArgumentMatchers.<FutureCallback<Boolean>>any())).thenAnswer((Answer<Cancellable>) invocation -> {
|
||||
final FutureCallback<Boolean> callback = invocation.getArgument(3);
|
||||
if (count.incrementAndGet() <= 3) {
|
||||
callback.completed(false);
|
||||
|
@ -437,18 +338,9 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
callback.completed(true);
|
||||
}
|
||||
return cancellable;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
impl.updateEntry(key, new HttpCacheCASOperation() {
|
||||
|
||||
@Override
|
||||
public HttpCacheEntry execute(final HttpCacheEntry existing) throws ResourceIOException {
|
||||
return updatedValue;
|
||||
}
|
||||
|
||||
}, operationCallback);
|
||||
impl.updateEntry(key, existing -> updatedValue, operationCallback);
|
||||
|
||||
Mockito.verify(impl, Mockito.times(3)).getForUpdateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.<FutureCallback<String>>any());
|
||||
Mockito.verify(impl, Mockito.times(3)).getStorageObject("stuff");
|
||||
|
@ -472,10 +364,7 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
|
||||
when(impl.bulkRestore(
|
||||
ArgumentMatchers.<String>anyCollection(),
|
||||
ArgumentMatchers.<FutureCallback<Map<String, byte[]>>>any())).thenAnswer(new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
ArgumentMatchers.<FutureCallback<Map<String, byte[]>>>any())).thenAnswer((Answer<Cancellable>) invocation -> {
|
||||
final Collection<String> keys = invocation.getArgument(0);
|
||||
final FutureCallback<Map<String, byte[]>> callback = invocation.getArgument(1);
|
||||
final Map<String, byte[]> resultMap = new HashMap<>();
|
||||
|
@ -487,7 +376,6 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
}
|
||||
callback.completed(resultMap);
|
||||
return cancellable;
|
||||
}
|
||||
});
|
||||
|
||||
impl.getEntries(Arrays.asList(key1, key2), bulkCacheEntryCallback);
|
||||
|
@ -521,10 +409,7 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
|
||||
when(impl.bulkRestore(
|
||||
ArgumentMatchers.<String>anyCollection(),
|
||||
ArgumentMatchers.<FutureCallback<Map<String, byte[]>>>any())).thenAnswer(new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
ArgumentMatchers.<FutureCallback<Map<String, byte[]>>>any())).thenAnswer((Answer<Cancellable>) invocation -> {
|
||||
final Collection<String> keys = invocation.getArgument(0);
|
||||
final FutureCallback<Map<String, byte[]>> callback = invocation.getArgument(1);
|
||||
final Map<String, byte[]> resultMap = new HashMap<>();
|
||||
|
@ -536,7 +421,6 @@ public class TestAbstractSerializingAsyncCacheStorage {
|
|||
}
|
||||
callback.completed(resultMap);
|
||||
return cancellable;
|
||||
}
|
||||
});
|
||||
|
||||
impl.getEntries(Arrays.asList(key1, key2), bulkCacheEntryCallback);
|
||||
|
|
|
@ -35,7 +35,6 @@ import java.util.Collection;
|
|||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.hc.client5.http.cache.HttpCacheCASOperation;
|
||||
import org.apache.hc.client5.http.cache.HttpCacheEntry;
|
||||
import org.apache.hc.client5.http.cache.HttpCacheStorageEntry;
|
||||
import org.apache.hc.client5.http.cache.HttpCacheUpdateException;
|
||||
|
@ -48,7 +47,6 @@ import org.mockito.Answers;
|
|||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
@SuppressWarnings("boxing") // test code
|
||||
|
@ -143,14 +141,9 @@ public class TestAbstractSerializingCacheStorage {
|
|||
when(impl.digestToStorageKey(key)).thenReturn("bar");
|
||||
when(impl.getForUpdateCAS("bar")).thenReturn(null);
|
||||
|
||||
impl.updateEntry(key, new HttpCacheCASOperation() {
|
||||
|
||||
@Override
|
||||
public HttpCacheEntry execute(final HttpCacheEntry existing) throws ResourceIOException {
|
||||
impl.updateEntry(key, existing -> {
|
||||
Assert.assertThat(existing, CoreMatchers.nullValue());
|
||||
return updatedValue;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
verify(impl).getForUpdateCAS("bar");
|
||||
|
@ -168,14 +161,7 @@ public class TestAbstractSerializingCacheStorage {
|
|||
when(impl.getStorageObject("stuff")).thenReturn(serialize(key, existingValue));
|
||||
when(impl.updateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.eq("stuff"), ArgumentMatchers.<byte[]>any())).thenReturn(true);
|
||||
|
||||
impl.updateEntry(key, new HttpCacheCASOperation() {
|
||||
|
||||
@Override
|
||||
public HttpCacheEntry execute(final HttpCacheEntry existing) throws ResourceIOException {
|
||||
return updatedValue;
|
||||
}
|
||||
|
||||
});
|
||||
impl.updateEntry(key, existing -> updatedValue);
|
||||
|
||||
verify(impl).getForUpdateCAS("bar");
|
||||
verify(impl).getStorageObject("stuff");
|
||||
|
@ -193,14 +179,9 @@ public class TestAbstractSerializingCacheStorage {
|
|||
when(impl.getStorageObject("stuff")).thenReturn(serialize("not-foo", existingValue));
|
||||
when(impl.updateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.eq("stuff"), ArgumentMatchers.<byte[]>any())).thenReturn(true);
|
||||
|
||||
impl.updateEntry(key, new HttpCacheCASOperation() {
|
||||
|
||||
@Override
|
||||
public HttpCacheEntry execute(final HttpCacheEntry existing) throws ResourceIOException {
|
||||
impl.updateEntry(key, existing -> {
|
||||
Assert.assertThat(existing, CoreMatchers.nullValue());
|
||||
return updatedValue;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
verify(impl).getForUpdateCAS("bar");
|
||||
|
@ -219,14 +200,7 @@ public class TestAbstractSerializingCacheStorage {
|
|||
when(impl.getStorageObject("stuff")).thenReturn(serialize(key, existingValue));
|
||||
when(impl.updateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.eq("stuff"), ArgumentMatchers.<byte[]>any())).thenReturn(false, true);
|
||||
|
||||
impl.updateEntry(key, new HttpCacheCASOperation() {
|
||||
|
||||
@Override
|
||||
public HttpCacheEntry execute(final HttpCacheEntry existing) throws ResourceIOException {
|
||||
return updatedValue;
|
||||
}
|
||||
|
||||
});
|
||||
impl.updateEntry(key, existing -> updatedValue);
|
||||
|
||||
verify(impl, Mockito.times(2)).getForUpdateCAS("bar");
|
||||
verify(impl, Mockito.times(2)).getStorageObject("stuff");
|
||||
|
@ -245,14 +219,7 @@ public class TestAbstractSerializingCacheStorage {
|
|||
when(impl.updateCAS(ArgumentMatchers.eq("bar"), ArgumentMatchers.eq("stuff"), ArgumentMatchers.<byte[]>any())).thenReturn(false, false, false, true);
|
||||
|
||||
try {
|
||||
impl.updateEntry(key, new HttpCacheCASOperation() {
|
||||
|
||||
@Override
|
||||
public HttpCacheEntry execute(final HttpCacheEntry existing) throws ResourceIOException {
|
||||
return updatedValue;
|
||||
}
|
||||
|
||||
});
|
||||
impl.updateEntry(key, existing -> updatedValue);
|
||||
Assert.fail("HttpCacheUpdateException expected");
|
||||
} catch (final HttpCacheUpdateException ignore) {
|
||||
}
|
||||
|
@ -274,10 +241,7 @@ public class TestAbstractSerializingCacheStorage {
|
|||
when(impl.digestToStorageKey(key1)).thenReturn(storageKey1);
|
||||
when(impl.digestToStorageKey(key2)).thenReturn(storageKey2);
|
||||
|
||||
when(impl.bulkRestore(ArgumentMatchers.<String>anyCollection())).thenAnswer(new Answer<Map<String, byte[]>>() {
|
||||
|
||||
@Override
|
||||
public Map<String, byte[]> answer(final InvocationOnMock invocation) throws Throwable {
|
||||
when(impl.bulkRestore(ArgumentMatchers.<String>anyCollection())).thenAnswer((Answer<Map<String, byte[]>>) invocation -> {
|
||||
final Collection<String> keys = invocation.getArgument(0);
|
||||
final Map<String, byte[]> resultMap = new HashMap<>();
|
||||
if (keys.contains(storageKey1)) {
|
||||
|
@ -287,7 +251,6 @@ public class TestAbstractSerializingCacheStorage {
|
|||
resultMap.put(storageKey2, serialize(key2, value2));
|
||||
}
|
||||
return resultMap;
|
||||
}
|
||||
});
|
||||
|
||||
final Map<String, HttpCacheEntry> entryMap = impl.getEntries(Arrays.asList(key1, key2));
|
||||
|
@ -312,10 +275,7 @@ public class TestAbstractSerializingCacheStorage {
|
|||
when(impl.digestToStorageKey(key1)).thenReturn(storageKey1);
|
||||
when(impl.digestToStorageKey(key2)).thenReturn(storageKey2);
|
||||
|
||||
when(impl.bulkRestore(ArgumentMatchers.<String>anyCollection())).thenAnswer(new Answer<Map<String, byte[]>>() {
|
||||
|
||||
@Override
|
||||
public Map<String, byte[]> answer(final InvocationOnMock invocation) throws Throwable {
|
||||
when(impl.bulkRestore(ArgumentMatchers.<String>anyCollection())).thenAnswer((Answer<Map<String, byte[]>>) invocation -> {
|
||||
final Collection<String> keys = invocation.getArgument(0);
|
||||
final Map<String, byte[]> resultMap = new HashMap<>();
|
||||
if (keys.contains(storageKey1)) {
|
||||
|
@ -325,7 +285,6 @@ public class TestAbstractSerializingCacheStorage {
|
|||
resultMap.put(storageKey2, serialize("not foo", value2));
|
||||
}
|
||||
return resultMap;
|
||||
}
|
||||
});
|
||||
|
||||
final Map<String, HttpCacheEntry> entryMap = impl.getEntries(Arrays.asList(key1, key2));
|
||||
|
|
|
@ -55,7 +55,7 @@ public class TestCachedHttpResponseGenerator {
|
|||
|
||||
@Before
|
||||
public void setUp() {
|
||||
entry = HttpTestUtils.makeCacheEntry(new HashMap<String, String>());
|
||||
entry = HttpTestUtils.makeCacheEntry(new HashMap<>());
|
||||
request = HttpTestUtils.makeDefaultRequest();
|
||||
mockValidityPolicy = mock(CacheValidityPolicy.class);
|
||||
impl = new CachedHttpResponseGenerator(mockValidityPolicy);
|
||||
|
|
|
@ -170,7 +170,7 @@ public class TestCachingExec extends TestCachingExecChain {
|
|||
mockImplMethods(CALL_BACKEND);
|
||||
requestPolicyAllowsCaching(true);
|
||||
getCacheEntryReturns(null);
|
||||
getVariantCacheEntriesReturns(new HashMap<String,Variant>());
|
||||
getVariantCacheEntriesReturns(new HashMap<>());
|
||||
|
||||
requestIsFatallyNonCompliant(null);
|
||||
|
||||
|
|
|
@ -34,7 +34,6 @@ import java.util.Map;
|
|||
import org.apache.hc.client5.http.cache.HeaderConstants;
|
||||
import org.apache.hc.client5.http.cache.HttpCacheEntry;
|
||||
import org.apache.hc.client5.http.utils.DateUtils;
|
||||
import org.apache.hc.core5.function.Factory;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HeaderElement;
|
||||
import org.apache.hc.core5.http.HttpRequest;
|
||||
|
@ -53,14 +52,7 @@ public class TestConditionalRequestBuilder {
|
|||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
impl = new ConditionalRequestBuilder<>(new Factory<HttpRequest, HttpRequest>() {
|
||||
|
||||
@Override
|
||||
public HttpRequest create(final HttpRequest request) {
|
||||
return BasicRequestBuilder.copy(request).build();
|
||||
}
|
||||
|
||||
});
|
||||
impl = new ConditionalRequestBuilder<>(request -> BasicRequestBuilder.copy(request).build());
|
||||
request = new BasicHttpRequest("GET", "/");
|
||||
}
|
||||
|
||||
|
|
|
@ -55,7 +55,6 @@ import org.junit.runner.RunWith;
|
|||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
|
@ -83,14 +82,9 @@ public class TestDefaultAsyncCacheInvalidator {
|
|||
now = new Date();
|
||||
tenSecondsAgo = new Date(now.getTime() - 10 * 1000L);
|
||||
|
||||
when(cacheKeyResolver.resolve(ArgumentMatchers.<URI>any())).thenAnswer(new Answer<String>() {
|
||||
|
||||
@Override
|
||||
public String answer(final InvocationOnMock invocation) throws Throwable {
|
||||
when(cacheKeyResolver.resolve(ArgumentMatchers.<URI>any())).thenAnswer((Answer<String>) invocation -> {
|
||||
final URI uri = invocation.getArgument(0);
|
||||
return HttpCacheSupport.normalize(uri).toASCIIString();
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
host = new HttpHost("foo.example.com");
|
||||
|
@ -124,7 +118,7 @@ public class TestDefaultAsyncCacheInvalidator {
|
|||
|
||||
final URI uri = new URI("http://foo.example.com:80/");
|
||||
final String key = uri.toASCIIString();
|
||||
cacheEntryHasVariantMap(new HashMap<String,String>());
|
||||
cacheEntryHasVariantMap(new HashMap<>());
|
||||
|
||||
cacheReturnsEntryForUri(key, mockEntry);
|
||||
|
||||
|
@ -146,7 +140,7 @@ public class TestDefaultAsyncCacheInvalidator {
|
|||
|
||||
final URI uri = new URI("http://foo.example.com:80/");
|
||||
final String key = uri.toASCIIString();
|
||||
cacheEntryHasVariantMap(new HashMap<String,String>());
|
||||
cacheEntryHasVariantMap(new HashMap<>());
|
||||
|
||||
cacheReturnsEntryForUri(key, mockEntry);
|
||||
|
||||
|
@ -168,7 +162,7 @@ public class TestDefaultAsyncCacheInvalidator {
|
|||
|
||||
final URI uri = new URI("http://foo.example.com:80/");
|
||||
final String key = uri.toASCIIString();
|
||||
cacheEntryHasVariantMap(new HashMap<String,String>());
|
||||
cacheEntryHasVariantMap(new HashMap<>());
|
||||
|
||||
cacheReturnsEntryForUri(key, mockEntry);
|
||||
|
||||
|
@ -190,7 +184,7 @@ public class TestDefaultAsyncCacheInvalidator {
|
|||
|
||||
final URI uri = new URI("http://foo.example.com:80/");
|
||||
final String key = uri.toASCIIString();
|
||||
cacheEntryHasVariantMap(new HashMap<String,String>());
|
||||
cacheEntryHasVariantMap(new HashMap<>());
|
||||
|
||||
cacheReturnsEntryForUri(key, mockEntry);
|
||||
|
||||
|
@ -226,7 +220,7 @@ public class TestDefaultAsyncCacheInvalidator {
|
|||
final HttpRequest request = new BasicHttpRequest("GET", uri);
|
||||
|
||||
cacheEntryisForMethod("HEAD");
|
||||
cacheEntryHasVariantMap(new HashMap<String, String>());
|
||||
cacheEntryHasVariantMap(new HashMap<>());
|
||||
cacheReturnsEntryForUri(key, mockEntry);
|
||||
|
||||
impl.flushCacheEntriesInvalidatedByRequest(host, request, cacheKeyResolver, mockStorage, operationCallback);
|
||||
|
@ -679,15 +673,10 @@ public class TestDefaultAsyncCacheInvalidator {
|
|||
private void cacheReturnsEntryForUri(final String key, final HttpCacheEntry cacheEntry) {
|
||||
Mockito.when(mockStorage.getEntry(
|
||||
ArgumentMatchers.eq(key),
|
||||
ArgumentMatchers.<FutureCallback<HttpCacheEntry>>any())).thenAnswer(new Answer<Cancellable>() {
|
||||
|
||||
@Override
|
||||
public Cancellable answer(final InvocationOnMock invocation) throws Throwable {
|
||||
ArgumentMatchers.<FutureCallback<HttpCacheEntry>>any())).thenAnswer((Answer<Cancellable>) invocation -> {
|
||||
final FutureCallback<HttpCacheEntry> callback = invocation.getArgument(1);
|
||||
callback.completed(cacheEntry);
|
||||
return cancellable;
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -53,7 +53,6 @@ import org.junit.Test;
|
|||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
|
@ -77,14 +76,9 @@ public class TestDefaultCacheInvalidator {
|
|||
now = new Date();
|
||||
tenSecondsAgo = new Date(now.getTime() - 10 * 1000L);
|
||||
|
||||
when(cacheKeyResolver.resolve(ArgumentMatchers.<URI>any())).thenAnswer(new Answer<String>() {
|
||||
|
||||
@Override
|
||||
public String answer(final InvocationOnMock invocation) throws Throwable {
|
||||
when(cacheKeyResolver.resolve(ArgumentMatchers.<URI>any())).thenAnswer((Answer<String>) invocation -> {
|
||||
final URI uri = invocation.getArgument(0);
|
||||
return HttpCacheSupport.normalize(uri).toASCIIString();
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
host = new HttpHost("foo.example.com");
|
||||
|
@ -118,7 +112,7 @@ public class TestDefaultCacheInvalidator {
|
|||
|
||||
final URI uri = new URI("http://foo.example.com:80/");
|
||||
final String key = uri.toASCIIString();
|
||||
cacheEntryHasVariantMap(new HashMap<String,String>());
|
||||
cacheEntryHasVariantMap(new HashMap<>());
|
||||
|
||||
cacheReturnsEntryForUri(key);
|
||||
|
||||
|
@ -140,7 +134,7 @@ public class TestDefaultCacheInvalidator {
|
|||
|
||||
final URI uri = new URI("http://foo.example.com:80/");
|
||||
final String key = uri.toASCIIString();
|
||||
cacheEntryHasVariantMap(new HashMap<String,String>());
|
||||
cacheEntryHasVariantMap(new HashMap<>());
|
||||
|
||||
cacheReturnsEntryForUri(key);
|
||||
|
||||
|
@ -162,7 +156,7 @@ public class TestDefaultCacheInvalidator {
|
|||
|
||||
final URI uri = new URI("http://foo.example.com:80/");
|
||||
final String key = uri.toASCIIString();
|
||||
cacheEntryHasVariantMap(new HashMap<String,String>());
|
||||
cacheEntryHasVariantMap(new HashMap<>());
|
||||
|
||||
cacheReturnsEntryForUri(key);
|
||||
|
||||
|
@ -184,7 +178,7 @@ public class TestDefaultCacheInvalidator {
|
|||
|
||||
final URI uri = new URI("http://foo.example.com:80/");
|
||||
final String key = uri.toASCIIString();
|
||||
cacheEntryHasVariantMap(new HashMap<String,String>());
|
||||
cacheEntryHasVariantMap(new HashMap<>());
|
||||
|
||||
cacheReturnsEntryForUri(key);
|
||||
|
||||
|
@ -220,7 +214,7 @@ public class TestDefaultCacheInvalidator {
|
|||
final HttpRequest request = new BasicHttpRequest("GET", uri);
|
||||
|
||||
cacheEntryisForMethod("HEAD");
|
||||
cacheEntryHasVariantMap(new HashMap<String, String>());
|
||||
cacheEntryHasVariantMap(new HashMap<>());
|
||||
cacheReturnsEntryForUri(key);
|
||||
|
||||
impl.flushCacheEntriesInvalidatedByRequest(host, request, cacheKeyResolver, mockStorage);
|
||||
|
|
|
@ -41,12 +41,9 @@ public class TestPrefixKeyHashingScheme {
|
|||
|
||||
@Before
|
||||
public void setUp() {
|
||||
scheme = new KeyHashingScheme() {
|
||||
@Override
|
||||
public String hash(final String storageKey) {
|
||||
scheme = storageKey -> {
|
||||
assertEquals(KEY, storageKey);
|
||||
return "hash";
|
||||
}
|
||||
};
|
||||
impl = new PrefixKeyHashingScheme(PREFIX, scheme);
|
||||
}
|
||||
|
|
|
@ -173,7 +173,7 @@ public class Request {
|
|||
builder = RequestConfig.custom();
|
||||
}
|
||||
if (this.useExpectContinue != null) {
|
||||
builder.setExpectContinueEnabled(this.useExpectContinue);
|
||||
builder.setExpectContinueEnabled(this.useExpectContinue.booleanValue());
|
||||
}
|
||||
if (this.connectTimeout != null) {
|
||||
builder.setConnectTimeout(this.connectTimeout);
|
||||
|
|
|
@ -26,7 +26,6 @@
|
|||
*/
|
||||
package org.apache.hc.client5.http.examples.fluent;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
|
@ -37,11 +36,9 @@ import javax.xml.parsers.ParserConfigurationException;
|
|||
import org.apache.hc.client5.http.ClientProtocolException;
|
||||
import org.apache.hc.client5.http.HttpResponseException;
|
||||
import org.apache.hc.client5.http.fluent.Request;
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.HttpEntity;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
|
||||
import org.w3c.dom.Document;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
|
@ -53,10 +50,7 @@ public class FluentResponseHandling {
|
|||
|
||||
public static void main(final String... args)throws Exception {
|
||||
final Document result = Request.get("http://somehost/content")
|
||||
.execute().handleResponse(new HttpClientResponseHandler<Document>() {
|
||||
|
||||
@Override
|
||||
public Document handleResponse(final ClassicHttpResponse response) throws IOException {
|
||||
.execute().handleResponse(response -> {
|
||||
final int status = response.getCode();
|
||||
final HttpEntity entity = response.getEntity();
|
||||
if (status >= HttpStatus.SC_REDIRECTION) {
|
||||
|
@ -82,8 +76,6 @@ public class FluentResponseHandling {
|
|||
} catch (final SAXException ex) {
|
||||
throw new ClientProtocolException("Malformed XML document", ex);
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
// Do something useful with the result
|
||||
System.out.println(result);
|
||||
|
|
|
@ -54,7 +54,6 @@ import org.apache.hc.client5.http.protocol.HttpClientContext;
|
|||
import org.apache.hc.client5.testing.BasicTestAuthenticator;
|
||||
import org.apache.hc.client5.testing.auth.Authenticator;
|
||||
import org.apache.hc.core5.function.Decorator;
|
||||
import org.apache.hc.core5.function.Supplier;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.HttpHeaders;
|
||||
|
@ -89,14 +88,7 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
|
||||
@Override
|
||||
public final HttpHost start() throws Exception {
|
||||
return start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler requestHandler) {
|
||||
return new AuthenticatingAsyncDecorator(requestHandler, new BasicTestAuthenticator("test:test", "test realm"));
|
||||
}
|
||||
|
||||
});
|
||||
return start(requestHandler -> new AuthenticatingAsyncDecorator(requestHandler, new BasicTestAuthenticator("test:test", "test realm")));
|
||||
}
|
||||
|
||||
public final HttpHost start(
|
||||
|
@ -150,14 +142,7 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
|
||||
@Test
|
||||
public void testBasicAuthenticationNoCreds() throws Exception {
|
||||
server.register("*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
return new AsyncEchoHandler();
|
||||
}
|
||||
|
||||
});
|
||||
server.register("*", AsyncEchoHandler::new);
|
||||
final HttpHost target = start();
|
||||
|
||||
final TestCredentialsProvider credsProvider = new TestCredentialsProvider(null);
|
||||
|
@ -179,14 +164,7 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
|
||||
@Test
|
||||
public void testBasicAuthenticationFailure() throws Exception {
|
||||
server.register("*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
return new AsyncEchoHandler();
|
||||
}
|
||||
|
||||
});
|
||||
server.register("*", AsyncEchoHandler::new);
|
||||
final HttpHost target = start();
|
||||
|
||||
final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
|
||||
|
@ -209,14 +187,7 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
|
||||
@Test
|
||||
public void testBasicAuthenticationSuccess() throws Exception {
|
||||
server.register("*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
return new AsyncEchoHandler();
|
||||
}
|
||||
|
||||
});
|
||||
server.register("*", AsyncEchoHandler::new);
|
||||
final HttpHost target = start();
|
||||
|
||||
final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
|
||||
|
@ -240,14 +211,7 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
|
||||
@Test
|
||||
public void testBasicAuthenticationWithEntitySuccess() throws Exception {
|
||||
server.register("*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
return new AsyncEchoHandler();
|
||||
}
|
||||
|
||||
});
|
||||
server.register("*", AsyncEchoHandler::new);
|
||||
final HttpHost target = start();
|
||||
|
||||
final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
|
||||
|
@ -271,14 +235,7 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
|
||||
@Test
|
||||
public void testBasicAuthenticationExpectationFailure() throws Exception {
|
||||
server.register("*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
return new AsyncEchoHandler();
|
||||
}
|
||||
|
||||
});
|
||||
server.register("*", AsyncEchoHandler::new);
|
||||
final HttpHost target = start();
|
||||
|
||||
final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
|
||||
|
@ -300,14 +257,7 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
|
||||
@Test
|
||||
public void testBasicAuthenticationExpectationSuccess() throws Exception {
|
||||
server.register("*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
return new AsyncEchoHandler();
|
||||
}
|
||||
|
||||
});
|
||||
server.register("*", AsyncEchoHandler::new);
|
||||
final HttpHost target = start();
|
||||
|
||||
final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
|
||||
|
@ -332,14 +282,7 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
|
||||
@Test
|
||||
public void testBasicAuthenticationCredentialsCaching() throws Exception {
|
||||
server.register("*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
return new AsyncEchoHandler();
|
||||
}
|
||||
|
||||
});
|
||||
server.register("*", AsyncEchoHandler::new);
|
||||
|
||||
final AtomicLong count = new AtomicLong(0);
|
||||
setTargetAuthenticationStrategy(new DefaultAuthenticationStrategy() {
|
||||
|
@ -382,14 +325,7 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
|
||||
@Test
|
||||
public void testAuthenticationUserinfoInRequestSuccess() throws Exception {
|
||||
server.register("*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
return new AsyncEchoHandler();
|
||||
}
|
||||
|
||||
});
|
||||
server.register("*", AsyncEchoHandler::new);
|
||||
final HttpHost target = start();
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
@ -407,14 +343,7 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
|
||||
@Test
|
||||
public void testAuthenticationUserinfoInRequestFailure() throws Exception {
|
||||
server.register("*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
return new AsyncEchoHandler();
|
||||
}
|
||||
|
||||
});
|
||||
server.register("*", AsyncEchoHandler::new);
|
||||
final HttpHost target = start();
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
@ -431,20 +360,9 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
|
||||
@Test
|
||||
public void testAuthenticationUserinfoInRedirectSuccess() throws Exception {
|
||||
server.register("*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
return new AsyncEchoHandler();
|
||||
}
|
||||
|
||||
});
|
||||
server.register("*", AsyncEchoHandler::new);
|
||||
final HttpHost target = start();
|
||||
server.register("/thatway", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
return new AbstractSimpleServerExchangeHandler() {
|
||||
server.register("/thatway", () -> new AbstractSimpleServerExchangeHandler() {
|
||||
|
||||
@Override
|
||||
protected SimpleHttpResponse handle(
|
||||
|
@ -453,9 +371,6 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
response.addHeader(new BasicHeader("Location", target.getSchemeName() + "://test:test@" + target.toHostString() + "/"));
|
||||
return response;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
@ -473,23 +388,12 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
|
||||
@Test
|
||||
public void testReauthentication() throws Exception {
|
||||
server.register("*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
return new AsyncEchoHandler();
|
||||
}
|
||||
|
||||
});
|
||||
server.register("*", AsyncEchoHandler::new);
|
||||
final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
|
||||
new UsernamePasswordCredentials("test", "test".toCharArray()));
|
||||
|
||||
final Registry<AuthSchemeFactory> authSchemeRegistry = RegistryBuilder.<AuthSchemeFactory>create()
|
||||
.register("MyBasic", new AuthSchemeFactory() {
|
||||
|
||||
@Override
|
||||
public AuthScheme create(final HttpContext context) {
|
||||
return new BasicScheme() {
|
||||
.register("MyBasic", context -> new BasicScheme() {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
|
@ -498,9 +402,6 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
return "MyBasic";
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
})
|
||||
.build();
|
||||
setDefaultAuthSchemeRegistry(authSchemeRegistry);
|
||||
|
@ -520,11 +421,7 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
};
|
||||
|
||||
final HttpHost target = start(
|
||||
new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new AuthenticatingAsyncDecorator(exchangeHandler, authenticator) {
|
||||
exchangeHandler -> new AuthenticatingAsyncDecorator(exchangeHandler, authenticator) {
|
||||
|
||||
@Override
|
||||
protected void customizeUnauthorizedResponse(final HttpResponse unauthorized) {
|
||||
|
@ -532,9 +429,6 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, "MyBasic realm=\"test realm\"");
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
final RequestConfig config = RequestConfig.custom()
|
||||
|
@ -558,29 +452,15 @@ public abstract class AbstractHttpAsyncClientAuthentication<T extends CloseableH
|
|||
|
||||
@Test
|
||||
public void testAuthenticationFallback() throws Exception {
|
||||
server.register("*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
return new AsyncEchoHandler();
|
||||
}
|
||||
|
||||
});
|
||||
server.register("*", AsyncEchoHandler::new);
|
||||
final HttpHost target = start(
|
||||
new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new AuthenticatingAsyncDecorator(exchangeHandler, new BasicTestAuthenticator("test:test", "test realm")) {
|
||||
exchangeHandler -> new AuthenticatingAsyncDecorator(exchangeHandler, new BasicTestAuthenticator("test:test", "test realm")) {
|
||||
|
||||
@Override
|
||||
protected void customizeUnauthorizedResponse(final HttpResponse unauthorized) {
|
||||
unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, StandardAuthScheme.DIGEST + " realm=\"test realm\" invalid");
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
final TestCredentialsProvider credsProvider = new TestCredentialsProvider(
|
||||
|
|
|
@ -185,10 +185,7 @@ public abstract class AbstractHttpAsyncFundamentalsTest<T extends CloseableHttpA
|
|||
final int threadNum = 5;
|
||||
final ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
|
||||
for (int i = 0; i < threadNum; i++) {
|
||||
executorService.execute(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
executorService.execute(() -> {
|
||||
if (!Thread.currentThread().isInterrupted()) {
|
||||
httpclient.execute(
|
||||
SimpleRequestBuilder.get()
|
||||
|
@ -196,8 +193,6 @@ public abstract class AbstractHttpAsyncFundamentalsTest<T extends CloseableHttpA
|
|||
.setPath("/random/2048")
|
||||
.build(), callback);
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -28,7 +28,6 @@ package org.apache.hc.client5.testing.async;
|
|||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
|
@ -46,9 +45,7 @@ import org.apache.hc.client5.http.protocol.HttpClientContext;
|
|||
import org.apache.hc.client5.testing.OldPathRedirectResolver;
|
||||
import org.apache.hc.client5.testing.SSLTestContexts;
|
||||
import org.apache.hc.client5.testing.redirect.Redirect;
|
||||
import org.apache.hc.client5.testing.redirect.RedirectResolver;
|
||||
import org.apache.hc.core5.function.Decorator;
|
||||
import org.apache.hc.core5.function.Supplier;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
|
@ -100,16 +97,9 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect300() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MULTIPLE_CHOICES));
|
||||
}
|
||||
|
||||
});
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MULTIPLE_CHOICES)));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
final Future<SimpleHttpResponse> future = httpclient.execute(
|
||||
|
@ -128,16 +118,9 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect301() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_PERMANENTLY));
|
||||
}
|
||||
|
||||
});
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_PERMANENTLY)));
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
final Future<SimpleHttpResponse> future = httpclient.execute(
|
||||
SimpleRequestBuilder.get()
|
||||
|
@ -156,16 +139,9 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect302() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY));
|
||||
}
|
||||
|
||||
});
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY)));
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
final Future<SimpleHttpResponse> future = httpclient.execute(
|
||||
SimpleRequestBuilder.get()
|
||||
|
@ -184,27 +160,15 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect302NoLocation() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new RedirectResolver() {
|
||||
|
||||
@Override
|
||||
public Redirect resolve(final URI requestUri) throws URISyntaxException {
|
||||
requestUri -> {
|
||||
final String path = requestUri.getPath();
|
||||
if (path.startsWith("/oldlocation")) {
|
||||
return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, null);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
}));
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
final Future<SimpleHttpResponse> future = httpclient.execute(
|
||||
SimpleRequestBuilder.get()
|
||||
|
@ -222,16 +186,9 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect303() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_SEE_OTHER));
|
||||
}
|
||||
|
||||
});
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_SEE_OTHER)));
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
final Future<SimpleHttpResponse> future = httpclient.execute(
|
||||
SimpleRequestBuilder.get()
|
||||
|
@ -250,21 +207,13 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect304() throws Exception {
|
||||
server.register("/oldlocation/*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
|
||||
return new AbstractSimpleServerExchangeHandler() {
|
||||
server.register("/oldlocation/*", () -> new AbstractSimpleServerExchangeHandler() {
|
||||
|
||||
@Override
|
||||
protected SimpleHttpResponse handle(final SimpleHttpRequest request,
|
||||
final HttpCoreContext context) throws HttpException {
|
||||
return SimpleHttpResponse.create(HttpStatus.SC_NOT_MODIFIED, (String) null);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
});
|
||||
final HttpHost target = start();
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
@ -284,21 +233,13 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect305() throws Exception {
|
||||
server.register("/oldlocation/*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
|
||||
return new AbstractSimpleServerExchangeHandler() {
|
||||
server.register("/oldlocation/*", () -> new AbstractSimpleServerExchangeHandler() {
|
||||
|
||||
@Override
|
||||
protected SimpleHttpResponse handle(final SimpleHttpRequest request,
|
||||
final HttpCoreContext context) throws HttpException {
|
||||
return SimpleHttpResponse.create(HttpStatus.SC_USE_PROXY, (String) null);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
});
|
||||
final HttpHost target = start();
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
@ -318,16 +259,9 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect307() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_TEMPORARY_REDIRECT));
|
||||
}
|
||||
|
||||
});
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_TEMPORARY_REDIRECT)));
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
final Future<SimpleHttpResponse> future = httpclient.execute(
|
||||
SimpleRequestBuilder.get()
|
||||
|
@ -346,17 +280,10 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test(expected=ExecutionException.class)
|
||||
public void testMaxRedirectCheck() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new OldPathRedirectResolver("/circular-oldlocation/", "/circular-oldlocation/",
|
||||
HttpStatus.SC_MOVED_TEMPORARILY));
|
||||
}
|
||||
|
||||
});
|
||||
HttpStatus.SC_MOVED_TEMPORARILY)));
|
||||
|
||||
final RequestConfig config = RequestConfig.custom()
|
||||
.setCircularRedirectsAllowed(true)
|
||||
|
@ -376,17 +303,10 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test(expected=ExecutionException.class)
|
||||
public void testCircularRedirect() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new OldPathRedirectResolver("/circular-oldlocation/", "/circular-oldlocation/",
|
||||
HttpStatus.SC_MOVED_TEMPORARILY));
|
||||
}
|
||||
|
||||
});
|
||||
HttpStatus.SC_MOVED_TEMPORARILY)));
|
||||
|
||||
final RequestConfig config = RequestConfig.custom()
|
||||
.setCircularRedirectsAllowed(false)
|
||||
|
@ -407,16 +327,9 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test
|
||||
public void testPostRedirect() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/echo", HttpStatus.SC_TEMPORARY_REDIRECT));
|
||||
}
|
||||
|
||||
});
|
||||
new OldPathRedirectResolver("/oldlocation", "/echo", HttpStatus.SC_TEMPORARY_REDIRECT)));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
final Future<SimpleHttpResponse> future = httpclient.execute(
|
||||
|
@ -437,16 +350,9 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test
|
||||
public void testPostRedirectSeeOther() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/echo", HttpStatus.SC_SEE_OTHER));
|
||||
}
|
||||
|
||||
});
|
||||
new OldPathRedirectResolver("/oldlocation", "/echo", HttpStatus.SC_SEE_OTHER)));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
final Future<SimpleHttpResponse> future = httpclient.execute(
|
||||
|
@ -467,28 +373,16 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test
|
||||
public void testRelativeRedirect() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new RedirectResolver() {
|
||||
|
||||
@Override
|
||||
public Redirect resolve(final URI requestUri) throws URISyntaxException {
|
||||
requestUri -> {
|
||||
final String path = requestUri.getPath();
|
||||
if (path.startsWith("/oldlocation")) {
|
||||
return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, "/random/100");
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
}));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
||||
|
@ -509,28 +403,16 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test
|
||||
public void testRelativeRedirect2() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new RedirectResolver() {
|
||||
|
||||
@Override
|
||||
public Redirect resolve(final URI requestUri) throws URISyntaxException {
|
||||
requestUri -> {
|
||||
final String path = requestUri.getPath();
|
||||
if (path.equals("/random/oldlocation")) {
|
||||
return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, "100");
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
}));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
||||
|
@ -551,28 +433,16 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test(expected=ExecutionException.class)
|
||||
public void testRejectBogusRedirectLocation() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new RedirectResolver() {
|
||||
|
||||
@Override
|
||||
public Redirect resolve(final URI requestUri) throws URISyntaxException {
|
||||
requestUri -> {
|
||||
final String path = requestUri.getPath();
|
||||
if (path.equals("/oldlocation/")) {
|
||||
return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, "xxx://bogus");
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
}));
|
||||
|
||||
try {
|
||||
final Future<SimpleHttpResponse> future = httpclient.execute(
|
||||
|
@ -589,28 +459,16 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test(expected=ExecutionException.class)
|
||||
public void testRejectInvalidRedirectLocation() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new RedirectResolver() {
|
||||
|
||||
@Override
|
||||
public Redirect resolve(final URI requestUri) throws URISyntaxException {
|
||||
requestUri -> {
|
||||
final String path = requestUri.getPath();
|
||||
if (path.equals("/oldlocation/")) {
|
||||
return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, "/newlocation/?p=I have spaces");
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
}));
|
||||
|
||||
try {
|
||||
final Future<SimpleHttpResponse> future = httpclient.execute(
|
||||
|
@ -627,16 +485,9 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
|
||||
@Test
|
||||
public void testRedirectWithCookie() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY));
|
||||
}
|
||||
|
||||
});
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY)));
|
||||
|
||||
final CookieStore cookieStore = new BasicCookieStore();
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
@ -670,17 +521,12 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
final H2TestServer secondServer = new H2TestServer(IOReactorConfig.DEFAULT,
|
||||
scheme == URIScheme.HTTPS ? SSLTestContexts.createServerSSLContext() : null, null, null);
|
||||
try {
|
||||
secondServer.register("/random/*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
secondServer.register("/random/*", () -> {
|
||||
if (isReactive()) {
|
||||
return new ReactiveServerExchangeHandler(new ReactiveRandomProcessor());
|
||||
} else {
|
||||
return new AsyncRandomHandler();
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
final InetSocketAddress address2;
|
||||
if (version.greaterEquals(HttpVersion.HTTP_2)) {
|
||||
|
@ -690,16 +536,9 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
}
|
||||
final HttpHost redirectTarget = new HttpHost(scheme.name(), "localhost", address2.getPort());
|
||||
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new RedirectResolver() {
|
||||
|
||||
@Override
|
||||
public Redirect resolve(final URI requestUri) throws URISyntaxException {
|
||||
requestUri -> {
|
||||
final String path = requestUri.getPath();
|
||||
if (path.equals("/oldlocation")) {
|
||||
final URI location = new URIBuilder(requestUri)
|
||||
|
@ -709,12 +548,7 @@ public abstract class AbstractHttpAsyncRedirectsTest <T extends CloseableHttpAsy
|
|||
return new Redirect(HttpStatus.SC_MOVED_PERMANENTLY, location.toString());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
}));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
final Future<SimpleHttpResponse> future = httpclient.execute(
|
||||
|
|
|
@ -67,7 +67,6 @@ import org.junit.Test;
|
|||
import org.reactivestreams.Publisher;
|
||||
|
||||
import io.reactivex.Flowable;
|
||||
import io.reactivex.functions.Consumer;
|
||||
import io.reactivex.schedulers.Schedulers;
|
||||
|
||||
public abstract class AbstractHttpReactiveFundamentalsTest<T extends CloseableHttpAsyncClient> extends AbstractIntegrationTestBase<T> {
|
||||
|
@ -163,12 +162,7 @@ public abstract class AbstractHttpReactiveFundamentalsTest<T extends CloseableHt
|
|||
final Flowable<ByteBuffer> flowable = Flowable.fromPublisher(result.getBody())
|
||||
.observeOn(Schedulers.io()); // Stream the data on an RxJava scheduler, not a client thread
|
||||
ReactiveTestUtils.consumeStream(flowable)
|
||||
.subscribe(new Consumer<StreamDescription>() {
|
||||
@Override
|
||||
public void accept(final StreamDescription streamDescription) {
|
||||
responses.add(streamDescription);
|
||||
}
|
||||
});
|
||||
.subscribe(responses::add);
|
||||
}
|
||||
@Override
|
||||
public void failed(final Exception ex) { }
|
||||
|
@ -227,14 +221,11 @@ public abstract class AbstractHttpReactiveFundamentalsTest<T extends CloseableHt
|
|||
final int threadNum = 5;
|
||||
final ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
|
||||
for (int i = 0; i < threadNum; i++) {
|
||||
executorService.execute(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
executorService.execute(() -> {
|
||||
if (!Thread.currentThread().isInterrupted()) {
|
||||
final ReactiveResponseConsumer consumer = new ReactiveResponseConsumer(callback);
|
||||
httpclient.execute(AsyncRequestBuilder.get(target + "/random/2048").build(), consumer, null);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -28,9 +28,7 @@
|
|||
package org.apache.hc.client5.testing.async;
|
||||
|
||||
import org.apache.hc.client5.testing.SSLTestContexts;
|
||||
import org.apache.hc.core5.function.Supplier;
|
||||
import org.apache.hc.core5.http.URIScheme;
|
||||
import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
|
||||
import org.apache.hc.core5.reactive.ReactiveServerExchangeHandler;
|
||||
import org.apache.hc.core5.reactor.IOReactorConfig;
|
||||
import org.apache.hc.core5.testing.nio.H2TestServer;
|
||||
|
@ -68,29 +66,19 @@ public abstract class AbstractServerTestBase {
|
|||
.setSoTimeout(TIMEOUT)
|
||||
.build(),
|
||||
scheme == URIScheme.HTTPS ? SSLTestContexts.createServerSSLContext() : null, null, null);
|
||||
server.register("/echo/*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
server.register("/echo/*", () -> {
|
||||
if (isReactive()) {
|
||||
return new ReactiveServerExchangeHandler(new ReactiveEchoProcessor());
|
||||
} else {
|
||||
return new AsyncEchoHandler();
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
server.register("/random/*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
server.register("/random/*", () -> {
|
||||
if (isReactive()) {
|
||||
return new ReactiveServerExchangeHandler(new ReactiveRandomProcessor());
|
||||
} else {
|
||||
return new AsyncRandomHandler();
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -44,7 +44,6 @@ import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
|
|||
import org.apache.hc.client5.testing.OldPathRedirectResolver;
|
||||
import org.apache.hc.client5.testing.SSLTestContexts;
|
||||
import org.apache.hc.client5.testing.redirect.Redirect;
|
||||
import org.apache.hc.core5.function.Decorator;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpHeaders;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
|
@ -54,7 +53,6 @@ import org.apache.hc.core5.http.HttpStatus;
|
|||
import org.apache.hc.core5.http.HttpVersion;
|
||||
import org.apache.hc.core5.http.URIScheme;
|
||||
import org.apache.hc.core5.http.message.BasicHeader;
|
||||
import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
@ -125,17 +123,10 @@ public class TestHttp1AsyncRedirects extends AbstractHttpAsyncRedirectsTest<Clos
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect300NoKeepAlive() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MULTIPLE_CHOICES,
|
||||
Redirect.ConnControl.CLOSE));
|
||||
}
|
||||
|
||||
});
|
||||
Redirect.ConnControl.CLOSE)));
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
final Future<SimpleHttpResponse> future = httpclient.execute(SimpleRequestBuilder.get()
|
||||
.setHttpHost(target)
|
||||
|
@ -152,17 +143,10 @@ public class TestHttp1AsyncRedirects extends AbstractHttpAsyncRedirectsTest<Clos
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect301NoKeepAlive() throws Exception {
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_PERMANENTLY,
|
||||
Redirect.ConnControl.CLOSE));
|
||||
}
|
||||
|
||||
});
|
||||
Redirect.ConnControl.CLOSE)));
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
final Future<SimpleHttpResponse> future = httpclient.execute(SimpleRequestBuilder.get()
|
||||
.setHttpHost(target)
|
||||
|
@ -184,17 +168,10 @@ public class TestHttp1AsyncRedirects extends AbstractHttpAsyncRedirectsTest<Clos
|
|||
defaultHeaders.add(new BasicHeader(HttpHeaders.USER_AGENT, "my-test-client"));
|
||||
clientBuilder.setDefaultHeaders(defaultHeaders);
|
||||
|
||||
final HttpHost target = start(new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new RedirectingAsyncDecorator(
|
||||
final HttpHost target = start(exchangeHandler -> new RedirectingAsyncDecorator(
|
||||
exchangeHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_PERMANENTLY,
|
||||
Redirect.ConnControl.CLOSE));
|
||||
}
|
||||
|
||||
});
|
||||
Redirect.ConnControl.CLOSE)));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
||||
|
|
|
@ -28,7 +28,6 @@ package org.apache.hc.client5.testing.async;
|
|||
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import org.apache.hc.client5.http.HttpRoute;
|
||||
import org.apache.hc.client5.http.UserTokenHandler;
|
||||
import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
|
||||
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
|
||||
|
@ -41,7 +40,6 @@ import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBu
|
|||
import org.apache.hc.client5.http.protocol.HttpClientContext;
|
||||
import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
|
||||
import org.apache.hc.client5.testing.SSLTestContexts;
|
||||
import org.apache.hc.core5.function.Supplier;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.EndpointDetails;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
|
@ -49,7 +47,6 @@ import org.apache.hc.core5.http.HttpHost;
|
|||
import org.apache.hc.core5.http.HttpResponse;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.config.Http1Config;
|
||||
import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
|
||||
import org.apache.hc.core5.http.protocol.BasicHttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpCoreContext;
|
||||
|
@ -111,11 +108,7 @@ public class TestHttp1AsyncStatefulConnManagement extends AbstractIntegrationTes
|
|||
|
||||
@Test
|
||||
public void testStatefulConnections() throws Exception {
|
||||
server.register("*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
return new AbstractSimpleServerExchangeHandler() {
|
||||
server.register("*", () -> new AbstractSimpleServerExchangeHandler() {
|
||||
|
||||
@Override
|
||||
protected SimpleHttpResponse handle(
|
||||
|
@ -125,19 +118,9 @@ public class TestHttp1AsyncStatefulConnManagement extends AbstractIntegrationTes
|
|||
response.setBody("Whatever", ContentType.TEXT_PLAIN);
|
||||
return response;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
final UserTokenHandler userTokenHandler = new UserTokenHandler() {
|
||||
|
||||
@Override
|
||||
public Object getUserToken(final HttpRoute route, final HttpContext context) {
|
||||
return context.getAttribute("user");
|
||||
}
|
||||
|
||||
};
|
||||
final UserTokenHandler userTokenHandler = (route, context) -> context.getAttribute("user");
|
||||
clientBuilder.setUserTokenHandler(userTokenHandler);
|
||||
final HttpHost target = start();
|
||||
|
||||
|
@ -239,11 +222,7 @@ public class TestHttp1AsyncStatefulConnManagement extends AbstractIntegrationTes
|
|||
|
||||
@Test
|
||||
public void testRouteSpecificPoolRecylcing() throws Exception {
|
||||
server.register("*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
return new AbstractSimpleServerExchangeHandler() {
|
||||
server.register("*", () -> new AbstractSimpleServerExchangeHandler() {
|
||||
|
||||
@Override
|
||||
protected SimpleHttpResponse handle(
|
||||
|
@ -253,22 +232,12 @@ public class TestHttp1AsyncStatefulConnManagement extends AbstractIntegrationTes
|
|||
response.setBody("Whatever", ContentType.TEXT_PLAIN);
|
||||
return response;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
// This tests what happens when a maxed connection pool needs
|
||||
// to kill the last idle connection to a route to build a new
|
||||
// one to the same route.
|
||||
final UserTokenHandler userTokenHandler = new UserTokenHandler() {
|
||||
|
||||
@Override
|
||||
public Object getUserToken(final HttpRoute route, final HttpContext context) {
|
||||
return context.getAttribute("user");
|
||||
}
|
||||
|
||||
};
|
||||
final UserTokenHandler userTokenHandler = (route, context) -> context.getAttribute("user");
|
||||
clientBuilder.setUserTokenHandler(userTokenHandler);
|
||||
|
||||
final HttpHost target = start();
|
||||
|
|
|
@ -46,8 +46,6 @@ import org.apache.hc.client5.http.protocol.HttpClientContext;
|
|||
import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
|
||||
import org.apache.hc.client5.testing.BasicTestAuthenticator;
|
||||
import org.apache.hc.client5.testing.SSLTestContexts;
|
||||
import org.apache.hc.core5.function.Decorator;
|
||||
import org.apache.hc.core5.function.Supplier;
|
||||
import org.apache.hc.core5.http.HeaderElements;
|
||||
import org.apache.hc.core5.http.HttpHeaders;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
|
@ -58,7 +56,6 @@ import org.apache.hc.core5.http.URIScheme;
|
|||
import org.apache.hc.core5.http.config.Http1Config;
|
||||
import org.apache.hc.core5.http.config.Lookup;
|
||||
import org.apache.hc.core5.http.impl.HttpProcessors;
|
||||
import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
@ -136,29 +133,15 @@ public class TestHttp1ClientAuthentication extends AbstractHttpAsyncClientAuthen
|
|||
|
||||
@Test
|
||||
public void testBasicAuthenticationSuccessNonPersistentConnection() throws Exception {
|
||||
server.register("*", new Supplier<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler get() {
|
||||
return new AsyncEchoHandler();
|
||||
}
|
||||
|
||||
});
|
||||
server.register("*", AsyncEchoHandler::new);
|
||||
final HttpHost target = start(
|
||||
HttpProcessors.server(),
|
||||
new Decorator<AsyncServerExchangeHandler>() {
|
||||
|
||||
@Override
|
||||
public AsyncServerExchangeHandler decorate(final AsyncServerExchangeHandler exchangeHandler) {
|
||||
return new AuthenticatingAsyncDecorator(exchangeHandler, new BasicTestAuthenticator("test:test", "test realm")) {
|
||||
exchangeHandler -> new AuthenticatingAsyncDecorator(exchangeHandler, new BasicTestAuthenticator("test:test", "test realm")) {
|
||||
|
||||
@Override
|
||||
protected void customizeUnauthorizedResponse(final HttpResponse unauthorized) {
|
||||
unauthorized.addHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
},
|
||||
Http1Config.DEFAULT);
|
||||
|
||||
|
|
|
@ -27,7 +27,6 @@
|
|||
package org.apache.hc.client5.testing.fluent;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
|
@ -35,17 +34,11 @@ import org.apache.hc.client5.http.ClientProtocolException;
|
|||
import org.apache.hc.client5.http.fluent.Content;
|
||||
import org.apache.hc.client5.http.fluent.Request;
|
||||
import org.apache.hc.client5.testing.sync.LocalServerTestBase;
|
||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.HttpEntity;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
|
||||
import org.apache.hc.core5.http.io.HttpRequestHandler;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
@ -54,24 +47,8 @@ public class TestFluent extends LocalServerTestBase {
|
|||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
this.server.registerHandler("/", new HttpRequestHandler() {
|
||||
|
||||
@Override
|
||||
public void handle(
|
||||
final ClassicHttpRequest request,
|
||||
final ClassicHttpResponse response,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
response.setEntity(new StringEntity("All is well", ContentType.TEXT_PLAIN));
|
||||
}
|
||||
|
||||
});
|
||||
this.server.registerHandler("/echo", new HttpRequestHandler() {
|
||||
|
||||
@Override
|
||||
public void handle(
|
||||
final ClassicHttpRequest request,
|
||||
final ClassicHttpResponse response,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
this.server.registerHandler("/", (request, response, context) -> response.setEntity(new StringEntity("All is well", ContentType.TEXT_PLAIN)));
|
||||
this.server.registerHandler("/echo", (request, response, context) -> {
|
||||
HttpEntity responseEntity = null;
|
||||
final HttpEntity requestEntity = request.getEntity();
|
||||
if (requestEntity != null) {
|
||||
|
@ -86,8 +63,6 @@ public class TestFluent extends LocalServerTestBase {
|
|||
responseEntity = new StringEntity("echo", ContentType.TEXT_PLAIN);
|
||||
}
|
||||
response.setEntity(responseEntity);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -155,15 +130,7 @@ public class TestFluent extends LocalServerTestBase {
|
|||
Request.get(baseURL + "/").execute().returnContent();
|
||||
Request.get(baseURL + "/").execute().returnResponse();
|
||||
Request.get(baseURL + "/").execute().discardContent();
|
||||
Request.get(baseURL + "/").execute().handleResponse(new HttpClientResponseHandler<Object>() {
|
||||
|
||||
@Override
|
||||
public Object handleResponse(
|
||||
final ClassicHttpResponse response) throws IOException {
|
||||
return null;
|
||||
}
|
||||
|
||||
});
|
||||
Request.get(baseURL + "/").execute().handleResponse(response -> null);
|
||||
final File tmpFile = File.createTempFile("test", ".bin");
|
||||
try {
|
||||
Request.get(baseURL + "/").execute().saveContent(tmpFile);
|
||||
|
|
|
@ -39,11 +39,11 @@ import org.apache.hc.client5.http.auth.AuthCache;
|
|||
import org.apache.hc.client5.http.auth.AuthChallenge;
|
||||
import org.apache.hc.client5.http.auth.AuthScheme;
|
||||
import org.apache.hc.client5.http.auth.AuthSchemeFactory;
|
||||
import org.apache.hc.client5.http.auth.StandardAuthScheme;
|
||||
import org.apache.hc.client5.http.auth.AuthScope;
|
||||
import org.apache.hc.client5.http.auth.ChallengeType;
|
||||
import org.apache.hc.client5.http.auth.Credentials;
|
||||
import org.apache.hc.client5.http.auth.CredentialsProvider;
|
||||
import org.apache.hc.client5.http.auth.StandardAuthScheme;
|
||||
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||
|
@ -60,7 +60,6 @@ import org.apache.hc.client5.testing.BasicTestAuthenticator;
|
|||
import org.apache.hc.client5.testing.auth.Authenticator;
|
||||
import org.apache.hc.client5.testing.classic.AuthenticatingDecorator;
|
||||
import org.apache.hc.client5.testing.classic.EchoHandler;
|
||||
import org.apache.hc.core5.function.Decorator;
|
||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
import org.apache.hc.core5.http.EndpointDetails;
|
||||
|
@ -74,7 +73,6 @@ import org.apache.hc.core5.http.config.Registry;
|
|||
import org.apache.hc.core5.http.config.RegistryBuilder;
|
||||
import org.apache.hc.core5.http.impl.HttpProcessors;
|
||||
import org.apache.hc.core5.http.io.HttpRequestHandler;
|
||||
import org.apache.hc.core5.http.io.HttpServerRequestHandler;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.io.entity.InputStreamEntity;
|
||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||
|
@ -91,14 +89,7 @@ import org.junit.Test;
|
|||
public class TestClientAuthentication extends LocalServerTestBase {
|
||||
|
||||
public HttpHost start(final Authenticator authenticator) throws IOException {
|
||||
return super.start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new AuthenticatingDecorator(requestHandler, authenticator);
|
||||
}
|
||||
|
||||
});
|
||||
return super.start(null, requestHandler -> new AuthenticatingDecorator(requestHandler, authenticator));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -444,20 +435,12 @@ public class TestClientAuthentication extends LocalServerTestBase {
|
|||
@Test
|
||||
public void testAuthenticationUserinfoInRedirectSuccess() throws Exception {
|
||||
this.server.registerHandler("/*", new EchoHandler());
|
||||
this.server.registerHandler("/thatway", new HttpRequestHandler() {
|
||||
|
||||
@Override
|
||||
public void handle(
|
||||
final ClassicHttpRequest request,
|
||||
final ClassicHttpResponse response,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
this.server.registerHandler("/thatway", (request, response, context) -> {
|
||||
final EndpointDetails endpoint = (EndpointDetails) context.getAttribute(HttpCoreContext.CONNECTION_ENDPOINT);
|
||||
final InetSocketAddress socketAddress = (InetSocketAddress) endpoint.getLocalAddress();
|
||||
final int port = socketAddress.getPort();
|
||||
response.setCode(HttpStatus.SC_MOVED_PERMANENTLY);
|
||||
response.addHeader(new BasicHeader("Location", "http://test:test@localhost:" + port + "/secure"));
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
final HttpHost target = start(new BasicTestAuthenticator("test:test", "test realm") {
|
||||
|
@ -594,20 +577,13 @@ public class TestClientAuthentication extends LocalServerTestBase {
|
|||
|
||||
final HttpHost target = start(
|
||||
HttpProcessors.server(),
|
||||
new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new AuthenticatingDecorator(requestHandler, new BasicTestAuthenticator("test:test", "test realm")) {
|
||||
requestHandler -> new AuthenticatingDecorator(requestHandler, new BasicTestAuthenticator("test:test", "test realm")) {
|
||||
|
||||
@Override
|
||||
protected void customizeUnauthorizedResponse(final ClassicHttpResponse unauthorized) {
|
||||
unauthorized.addHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE);
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
@ -676,11 +652,7 @@ public class TestClientAuthentication extends LocalServerTestBase {
|
|||
|
||||
final HttpHost target = start(
|
||||
HttpProcessors.server(),
|
||||
new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new AuthenticatingDecorator(requestHandler, authenticator) {
|
||||
requestHandler -> new AuthenticatingDecorator(requestHandler, authenticator) {
|
||||
|
||||
@Override
|
||||
protected void customizeUnauthorizedResponse(final ClassicHttpResponse unauthorized) {
|
||||
|
@ -688,9 +660,6 @@ public class TestClientAuthentication extends LocalServerTestBase {
|
|||
unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, "MyBasic realm=\"test realm\"");
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
@ -712,20 +681,13 @@ public class TestClientAuthentication extends LocalServerTestBase {
|
|||
|
||||
final HttpHost target = start(
|
||||
HttpProcessors.server(),
|
||||
new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new AuthenticatingDecorator(requestHandler, new BasicTestAuthenticator("test:test", "test realm")) {
|
||||
requestHandler -> new AuthenticatingDecorator(requestHandler, new BasicTestAuthenticator("test:test", "test realm")) {
|
||||
|
||||
@Override
|
||||
protected void customizeUnauthorizedResponse(final ClassicHttpResponse unauthorized) {
|
||||
unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, StandardAuthScheme.DIGEST + " realm=\"test realm\" invalid");
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
|
|
@ -38,7 +38,6 @@ import org.apache.hc.client5.http.protocol.RedirectLocations;
|
|||
import org.apache.hc.client5.http.utils.URIUtils;
|
||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
import org.apache.hc.core5.http.EntityDetails;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
|
@ -112,17 +111,7 @@ public class TestClientRequestExecution extends LocalServerTestBase {
|
|||
public void testAutoGeneratedHeaders() throws Exception {
|
||||
this.server.registerHandler("*", new SimpleService());
|
||||
|
||||
final HttpRequestInterceptor interceptor = new HttpRequestInterceptor() {
|
||||
|
||||
@Override
|
||||
public void process(
|
||||
final HttpRequest request,
|
||||
final EntityDetails entityDetails,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
request.addHeader("my-header", "stuff");
|
||||
}
|
||||
|
||||
};
|
||||
final HttpRequestInterceptor interceptor = (request, entityDetails, context) -> request.addHeader("my-header", "stuff");
|
||||
|
||||
final HttpRequestRetryStrategy requestRetryStrategy = new HttpRequestRetryStrategy() {
|
||||
|
||||
|
|
|
@ -26,7 +26,6 @@
|
|||
*/
|
||||
package org.apache.hc.client5.testing.sync;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
|
||||
|
@ -36,15 +35,10 @@ import org.apache.hc.client5.http.cookie.Cookie;
|
|||
import org.apache.hc.client5.http.cookie.CookieStore;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.client5.http.protocol.HttpClientContext;
|
||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.io.HttpRequestHandler;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.message.BasicHeader;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
|
@ -55,12 +49,7 @@ public class TestCookieVirtualHost extends LocalServerTestBase {
|
|||
|
||||
@Test
|
||||
public void testCookieMatchingWithVirtualHosts() throws Exception {
|
||||
this.server.registerHandlerVirtual("app.mydomain.fr", "*", new HttpRequestHandler() {
|
||||
@Override
|
||||
public void handle(
|
||||
final ClassicHttpRequest request,
|
||||
final ClassicHttpResponse response,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
this.server.registerHandlerVirtual("app.mydomain.fr", "*", (request, response, context) -> {
|
||||
|
||||
final int n = Integer.parseInt(request.getFirstHeader("X-Request").getValue());
|
||||
switch (n) {
|
||||
|
@ -98,8 +87,6 @@ public class TestCookieVirtualHost extends LocalServerTestBase {
|
|||
Assert.fail("Unexpected value: " + n);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
final HttpHost target = start();
|
||||
|
|
|
@ -33,7 +33,6 @@ import org.apache.hc.client5.http.classic.methods.HttpGet;
|
|||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
|
||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
|
@ -43,10 +42,8 @@ import org.apache.hc.core5.http.impl.bootstrap.HttpServer;
|
|||
import org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap;
|
||||
import org.apache.hc.core5.http.impl.io.DefaultBHttpServerConnection;
|
||||
import org.apache.hc.core5.http.io.HttpConnectionFactory;
|
||||
import org.apache.hc.core5.http.io.HttpRequestHandler;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
|
@ -91,28 +88,10 @@ public class TestMalformedServerResponse {
|
|||
public void testNoContentResponseWithGarbage() throws Exception {
|
||||
try (final HttpServer server = ServerBootstrap.bootstrap()
|
||||
.setConnectionFactory(new BrokenServerConnectionFactory())
|
||||
.register("/nostuff", new HttpRequestHandler() {
|
||||
|
||||
@Override
|
||||
public void handle(
|
||||
final ClassicHttpRequest request,
|
||||
final ClassicHttpResponse response,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
response.setCode(HttpStatus.SC_NO_CONTENT);
|
||||
}
|
||||
|
||||
})
|
||||
.register("/stuff", new HttpRequestHandler() {
|
||||
|
||||
@Override
|
||||
public void handle(
|
||||
final ClassicHttpRequest request,
|
||||
final ClassicHttpResponse response,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
.register("/nostuff", (request, response, context) -> response.setCode(HttpStatus.SC_NO_CONTENT))
|
||||
.register("/stuff", (request, response, context) -> {
|
||||
response.setCode(HttpStatus.SC_OK);
|
||||
response.setEntity(new StringEntity("Some important stuff"));
|
||||
}
|
||||
|
||||
})
|
||||
.create()) {
|
||||
server.start();
|
||||
|
|
|
@ -28,7 +28,6 @@ package org.apache.hc.client5.testing.sync;
|
|||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.Collections;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
@ -47,7 +46,6 @@ import org.apache.hc.client5.http.protocol.RedirectLocations;
|
|||
import org.apache.hc.client5.testing.OldPathRedirectResolver;
|
||||
import org.apache.hc.client5.testing.classic.RedirectingDecorator;
|
||||
import org.apache.hc.client5.testing.redirect.Redirect;
|
||||
import org.apache.hc.client5.testing.redirect.RedirectResolver;
|
||||
import org.apache.hc.core5.function.Decorator;
|
||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
|
@ -58,7 +56,6 @@ import org.apache.hc.core5.http.HttpHost;
|
|||
import org.apache.hc.core5.http.HttpRequest;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.ProtocolException;
|
||||
import org.apache.hc.core5.http.io.HttpRequestHandler;
|
||||
import org.apache.hc.core5.http.io.HttpServerRequestHandler;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||
|
@ -76,16 +73,9 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect300() throws Exception {
|
||||
final HttpHost target = start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new RedirectingDecorator(
|
||||
final HttpHost target = start(null, requestHandler -> new RedirectingDecorator(
|
||||
requestHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MULTIPLE_CHOICES));
|
||||
}
|
||||
|
||||
});
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MULTIPLE_CHOICES)));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
final HttpGet httpget = new HttpGet("/oldlocation/100");
|
||||
|
@ -106,17 +96,10 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect300NoKeepAlive() throws Exception {
|
||||
final HttpHost target = start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new RedirectingDecorator(
|
||||
final HttpHost target = start(null, requestHandler -> new RedirectingDecorator(
|
||||
requestHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MULTIPLE_CHOICES,
|
||||
Redirect.ConnControl.CLOSE));
|
||||
}
|
||||
|
||||
});
|
||||
Redirect.ConnControl.CLOSE)));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
final HttpGet httpget = new HttpGet("/oldlocation/100");
|
||||
|
@ -137,16 +120,9 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect301() throws Exception {
|
||||
final HttpHost target = start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new RedirectingDecorator(
|
||||
final HttpHost target = start(null, requestHandler -> new RedirectingDecorator(
|
||||
requestHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_PERMANENTLY));
|
||||
}
|
||||
|
||||
});
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_PERMANENTLY)));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
||||
|
@ -172,16 +148,9 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect302() throws Exception {
|
||||
final HttpHost target = start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new RedirectingDecorator(
|
||||
final HttpHost target = start(null, requestHandler -> new RedirectingDecorator(
|
||||
requestHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY));
|
||||
}
|
||||
|
||||
});
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY)));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
||||
|
@ -200,27 +169,15 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect302NoLocation() throws Exception {
|
||||
final HttpHost target = start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new RedirectingDecorator(
|
||||
final HttpHost target = start(null, requestHandler -> new RedirectingDecorator(
|
||||
requestHandler,
|
||||
new RedirectResolver() {
|
||||
|
||||
@Override
|
||||
public Redirect resolve(final URI requestUri) throws URISyntaxException {
|
||||
requestUri -> {
|
||||
final String path = requestUri.getPath();
|
||||
if (path.startsWith("/oldlocation")) {
|
||||
return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, null);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
}));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
||||
|
@ -238,16 +195,9 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect303() throws Exception {
|
||||
final HttpHost target = start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new RedirectingDecorator(
|
||||
final HttpHost target = start(null, requestHandler -> new RedirectingDecorator(
|
||||
requestHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_SEE_OTHER));
|
||||
}
|
||||
|
||||
});
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_SEE_OTHER)));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
||||
|
@ -266,16 +216,9 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect304() throws Exception {
|
||||
this.server.registerHandler("/oldlocation/*", new HttpRequestHandler() {
|
||||
|
||||
@Override
|
||||
public void handle(final ClassicHttpRequest request,
|
||||
final ClassicHttpResponse response,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
this.server.registerHandler("/oldlocation/*", (request, response, context) -> {
|
||||
response.setCode(HttpStatus.SC_NOT_MODIFIED);
|
||||
response.addHeader(HttpHeaders.LOCATION, "/random/100");
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
final HttpHost target = start();
|
||||
|
@ -301,16 +244,9 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect305() throws Exception {
|
||||
this.server.registerHandler("/oldlocation/*", new HttpRequestHandler() {
|
||||
|
||||
@Override
|
||||
public void handle(final ClassicHttpRequest request,
|
||||
final ClassicHttpResponse response,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
this.server.registerHandler("/oldlocation/*", (request, response, context) -> {
|
||||
response.setCode(HttpStatus.SC_USE_PROXY);
|
||||
response.addHeader(HttpHeaders.LOCATION, "/random/100");
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
final HttpHost target = start();
|
||||
|
@ -336,16 +272,9 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test
|
||||
public void testBasicRedirect307() throws Exception {
|
||||
final HttpHost target = start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new RedirectingDecorator(
|
||||
final HttpHost target = start(null, requestHandler -> new RedirectingDecorator(
|
||||
requestHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_TEMPORARY_REDIRECT));
|
||||
}
|
||||
|
||||
});
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_TEMPORARY_REDIRECT)));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
||||
|
@ -364,17 +293,10 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test(expected = ClientProtocolException.class)
|
||||
public void testMaxRedirectCheck() throws Exception {
|
||||
final HttpHost target = start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new RedirectingDecorator(
|
||||
final HttpHost target = start(null, requestHandler -> new RedirectingDecorator(
|
||||
requestHandler,
|
||||
new OldPathRedirectResolver("/circular-oldlocation/", "/circular-oldlocation/",
|
||||
HttpStatus.SC_MOVED_TEMPORARILY));
|
||||
}
|
||||
|
||||
});
|
||||
HttpStatus.SC_MOVED_TEMPORARILY)));
|
||||
|
||||
final RequestConfig config = RequestConfig.custom()
|
||||
.setCircularRedirectsAllowed(true)
|
||||
|
@ -393,17 +315,10 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test(expected = ClientProtocolException.class)
|
||||
public void testCircularRedirect() throws Exception {
|
||||
final HttpHost target = start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new RedirectingDecorator(
|
||||
final HttpHost target = start(null, requestHandler -> new RedirectingDecorator(
|
||||
requestHandler,
|
||||
new OldPathRedirectResolver("/circular-oldlocation/", "/circular-oldlocation/",
|
||||
HttpStatus.SC_MOVED_TEMPORARILY));
|
||||
}
|
||||
|
||||
});
|
||||
HttpStatus.SC_MOVED_TEMPORARILY)));
|
||||
|
||||
final RequestConfig config = RequestConfig.custom()
|
||||
.setCircularRedirectsAllowed(false)
|
||||
|
@ -421,16 +336,9 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test
|
||||
public void testPostRedirectSeeOther() throws Exception {
|
||||
final HttpHost target = start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new RedirectingDecorator(
|
||||
final HttpHost target = start(null, requestHandler -> new RedirectingDecorator(
|
||||
requestHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/echo", HttpStatus.SC_SEE_OTHER));
|
||||
}
|
||||
|
||||
});
|
||||
new OldPathRedirectResolver("/oldlocation", "/echo", HttpStatus.SC_SEE_OTHER)));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
||||
|
@ -452,28 +360,16 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test
|
||||
public void testRelativeRedirect() throws Exception {
|
||||
final HttpHost target = start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new RedirectingDecorator(
|
||||
final HttpHost target = start(null, requestHandler -> new RedirectingDecorator(
|
||||
requestHandler,
|
||||
new RedirectResolver() {
|
||||
|
||||
@Override
|
||||
public Redirect resolve(final URI requestUri) throws URISyntaxException {
|
||||
requestUri -> {
|
||||
final String path = requestUri.getPath();
|
||||
if (path.startsWith("/oldlocation")) {
|
||||
return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, "/random/100");
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
}));
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
||||
final HttpGet httpget = new HttpGet("/oldlocation/stuff");
|
||||
|
@ -491,28 +387,16 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test
|
||||
public void testRelativeRedirect2() throws Exception {
|
||||
final HttpHost target = start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new RedirectingDecorator(
|
||||
final HttpHost target = start(null, requestHandler -> new RedirectingDecorator(
|
||||
requestHandler,
|
||||
new RedirectResolver() {
|
||||
|
||||
@Override
|
||||
public Redirect resolve(final URI requestUri) throws URISyntaxException {
|
||||
requestUri -> {
|
||||
final String path = requestUri.getPath();
|
||||
if (path.equals("/random/oldlocation")) {
|
||||
return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, "100");
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
}));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
||||
|
@ -532,28 +416,16 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test(expected = ClientProtocolException.class)
|
||||
public void testRejectBogusRedirectLocation() throws Exception {
|
||||
final HttpHost target = start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new RedirectingDecorator(
|
||||
final HttpHost target = start(null, requestHandler -> new RedirectingDecorator(
|
||||
requestHandler,
|
||||
new RedirectResolver() {
|
||||
|
||||
@Override
|
||||
public Redirect resolve(final URI requestUri) throws URISyntaxException {
|
||||
requestUri -> {
|
||||
final String path = requestUri.getPath();
|
||||
if (path.equals("/oldlocation")) {
|
||||
return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, "xxx://bogus");
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
}));
|
||||
|
||||
final HttpGet httpget = new HttpGet("/oldlocation");
|
||||
|
||||
|
@ -568,28 +440,16 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test(expected = ClientProtocolException.class)
|
||||
public void testRejectInvalidRedirectLocation() throws Exception {
|
||||
final HttpHost target = start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new RedirectingDecorator(
|
||||
final HttpHost target = start(null, requestHandler -> new RedirectingDecorator(
|
||||
requestHandler,
|
||||
new RedirectResolver() {
|
||||
|
||||
@Override
|
||||
public Redirect resolve(final URI requestUri) throws URISyntaxException {
|
||||
requestUri -> {
|
||||
final String path = requestUri.getPath();
|
||||
if (path.equals("/oldlocation")) {
|
||||
return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, "/newlocation/?p=I have spaces");
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
}));
|
||||
|
||||
final HttpGet httpget = new HttpGet("/oldlocation");
|
||||
|
||||
|
@ -603,16 +463,9 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
|
||||
@Test
|
||||
public void testRedirectWithCookie() throws Exception {
|
||||
final HttpHost target = start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new RedirectingDecorator(
|
||||
final HttpHost target = start(null, requestHandler -> new RedirectingDecorator(
|
||||
requestHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY));
|
||||
}
|
||||
|
||||
});
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY)));
|
||||
|
||||
final CookieStore cookieStore = new BasicCookieStore();
|
||||
|
||||
|
@ -644,16 +497,9 @@ public class TestRedirects extends LocalServerTestBase {
|
|||
public void testDefaultHeadersRedirect() throws Exception {
|
||||
this.clientBuilder.setDefaultHeaders(Collections.singletonList(new BasicHeader(HttpHeaders.USER_AGENT, "my-test-client")));
|
||||
|
||||
final HttpHost target = start(null, new Decorator<HttpServerRequestHandler>() {
|
||||
|
||||
@Override
|
||||
public HttpServerRequestHandler decorate(final HttpServerRequestHandler requestHandler) {
|
||||
return new RedirectingDecorator(
|
||||
final HttpHost target = start(null, requestHandler -> new RedirectingDecorator(
|
||||
requestHandler,
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY));
|
||||
}
|
||||
|
||||
});
|
||||
new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY)));
|
||||
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
|
||||
|
|
|
@ -33,13 +33,10 @@ import java.net.Socket;
|
|||
import java.security.KeyManagementException;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLException;
|
||||
import javax.net.ssl.SSLParameters;
|
||||
import javax.net.ssl.SSLSession;
|
||||
import javax.net.ssl.SSLSocket;
|
||||
|
||||
|
@ -49,7 +46,6 @@ import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
|
|||
import org.apache.hc.client5.http.ssl.TrustAllStrategy;
|
||||
import org.apache.hc.client5.http.ssl.TrustSelfSignedStrategy;
|
||||
import org.apache.hc.client5.testing.SSLTestContexts;
|
||||
import org.apache.hc.core5.function.Callback;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
import org.apache.hc.core5.http.impl.bootstrap.HttpServer;
|
||||
import org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap;
|
||||
|
@ -190,14 +186,7 @@ public class TestSSLSocketFactory {
|
|||
// @formatter:off
|
||||
this.server = ServerBootstrap.bootstrap()
|
||||
.setSslContext(SSLTestContexts.createServerSSLContext())
|
||||
.setSslSetupHandler(new Callback<SSLParameters>() {
|
||||
|
||||
@Override
|
||||
public void execute(final SSLParameters sslParameters) {
|
||||
sslParameters.setNeedClientAuth(true);
|
||||
}
|
||||
|
||||
})
|
||||
.setSslSetupHandler(sslParameters -> sslParameters.setNeedClientAuth(true))
|
||||
.create();
|
||||
// @formatter:on
|
||||
this.server.start();
|
||||
|
@ -252,14 +241,7 @@ public class TestSSLSocketFactory {
|
|||
|
||||
@Test
|
||||
public void testSSLTrustVerificationOverrideWithCustsom() throws Exception {
|
||||
final TrustStrategy trustStrategy = new TrustStrategy() {
|
||||
|
||||
@Override
|
||||
public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
|
||||
return chain.length == 1;
|
||||
}
|
||||
|
||||
};
|
||||
final TrustStrategy trustStrategy = (chain, authType) -> chain.length == 1;
|
||||
testSSLTrustVerificationOverride(trustStrategy);
|
||||
}
|
||||
|
||||
|
@ -307,14 +289,7 @@ public class TestSSLSocketFactory {
|
|||
// @formatter:off
|
||||
this.server = ServerBootstrap.bootstrap()
|
||||
.setSslContext(SSLTestContexts.createServerSSLContext())
|
||||
.setSslSetupHandler(new Callback<SSLParameters>() {
|
||||
|
||||
@Override
|
||||
public void execute(final SSLParameters sslParameters) {
|
||||
sslParameters.setProtocols(new String[] {"SSLv3"});
|
||||
}
|
||||
|
||||
})
|
||||
.setSslSetupHandler(sslParameters -> sslParameters.setProtocols(new String[] {"SSLv3"}))
|
||||
.create();
|
||||
// @formatter:on
|
||||
this.server.start();
|
||||
|
@ -362,14 +337,7 @@ public class TestSSLSocketFactory {
|
|||
// @formatter:off
|
||||
this.server = ServerBootstrap.bootstrap()
|
||||
.setSslContext(SSLTestContexts.createServerSSLContext())
|
||||
.setSslSetupHandler(new Callback<SSLParameters>() {
|
||||
|
||||
@Override
|
||||
public void execute(final SSLParameters sslParameters) {
|
||||
sslParameters.setProtocols(new String[] {cipherSuite});
|
||||
}
|
||||
|
||||
})
|
||||
.setSslSetupHandler(sslParameters -> sslParameters.setProtocols(new String[] {cipherSuite}))
|
||||
.create();
|
||||
// @formatter:on
|
||||
this.server.start();
|
||||
|
|
|
@ -28,7 +28,6 @@ package org.apache.hc.client5.testing.sync;
|
|||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.hc.client5.http.HttpRoute;
|
||||
import org.apache.hc.client5.http.UserTokenHandler;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
|
@ -80,14 +79,9 @@ public class TestStatefulConnManagement extends LocalServerTestBase {
|
|||
this.connManager.setMaxTotal(workerCount);
|
||||
this.connManager.setDefaultMaxPerRoute(workerCount);
|
||||
|
||||
final UserTokenHandler userTokenHandler = new UserTokenHandler() {
|
||||
|
||||
@Override
|
||||
public Object getUserToken(final HttpRoute route, final HttpContext context) {
|
||||
final UserTokenHandler userTokenHandler = (route, context) -> {
|
||||
final String id = (String) context.getAttribute("user");
|
||||
return id;
|
||||
}
|
||||
|
||||
};
|
||||
this.clientBuilder.setUserTokenHandler(userTokenHandler);
|
||||
|
||||
|
@ -199,14 +193,7 @@ public class TestStatefulConnManagement extends LocalServerTestBase {
|
|||
this.connManager.setMaxTotal(maxConn);
|
||||
this.connManager.setDefaultMaxPerRoute(maxConn);
|
||||
|
||||
final UserTokenHandler userTokenHandler = new UserTokenHandler() {
|
||||
|
||||
@Override
|
||||
public Object getUserToken(final HttpRoute route, final HttpContext context) {
|
||||
return context.getAttribute("user");
|
||||
}
|
||||
|
||||
};
|
||||
final UserTokenHandler userTokenHandler = (route, context) -> context.getAttribute("user");
|
||||
|
||||
this.clientBuilder.setUserTokenHandler(userTokenHandler);
|
||||
|
||||
|
|
|
@ -26,28 +26,20 @@
|
|||
*/
|
||||
package org.apache.hc.client5.testing.sync;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.hc.client5.http.auth.AuthScheme;
|
||||
import org.apache.hc.client5.http.auth.AuthSchemeFactory;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.auth.StandardAuthScheme;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
|
||||
import org.apache.hc.client5.http.impl.win.WinHttpClients;
|
||||
import org.apache.hc.client5.http.impl.win.WindowsNegotiateSchemeGetTokenFail;
|
||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.HttpHeaders;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.config.Registry;
|
||||
import org.apache.hc.core5.http.config.RegistryBuilder;
|
||||
import org.apache.hc.core5.http.io.HttpRequestHandler;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.junit.Assume;
|
||||
import org.junit.Test;
|
||||
|
||||
|
@ -58,17 +50,9 @@ public class TestWindowsNegotiateScheme extends LocalServerTestBase {
|
|||
|
||||
@Test(timeout=30000) // this timeout (in ms) needs to be extended if you're actively debugging the code
|
||||
public void testNoInfiniteLoopOnSPNOutsideDomain() throws Exception {
|
||||
this.server.registerHandler("/", new HttpRequestHandler() {
|
||||
|
||||
@Override
|
||||
public void handle(
|
||||
final ClassicHttpRequest request,
|
||||
final ClassicHttpResponse response,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
this.server.registerHandler("/", (request, response, context) -> {
|
||||
response.addHeader(HttpHeaders.WWW_AUTHENTICATE, StandardAuthScheme.SPNEGO);
|
||||
response.setCode(HttpStatus.SC_UNAUTHORIZED);
|
||||
}
|
||||
|
||||
});
|
||||
Assume.assumeTrue("Test can only be run on Windows", WinHttpClients.isWinAuthAvailable());
|
||||
|
||||
|
@ -81,12 +65,7 @@ public class TestWindowsNegotiateScheme extends LocalServerTestBase {
|
|||
// you can contact the server that authenticated you." is associated with SEC_E_DOWNGRADE_DETECTED.
|
||||
|
||||
final Registry<AuthSchemeFactory> authSchemeRegistry = RegistryBuilder.<AuthSchemeFactory>create()
|
||||
.register(StandardAuthScheme.SPNEGO, new AuthSchemeFactory() {
|
||||
@Override
|
||||
public AuthScheme create(final HttpContext context) {
|
||||
return new WindowsNegotiateSchemeGetTokenFail(StandardAuthScheme.SPNEGO, "HTTP/example.com");
|
||||
}
|
||||
}).build();
|
||||
.register(StandardAuthScheme.SPNEGO, context -> new WindowsNegotiateSchemeGetTokenFail(StandardAuthScheme.SPNEGO, "HTTP/example.com")).build();
|
||||
final CloseableHttpClient customClient = HttpClientBuilder.create()
|
||||
.setDefaultAuthSchemeRegistry(authSchemeRegistry).build();
|
||||
|
||||
|
|
|
@ -55,11 +55,7 @@ public class Header implements Iterable<MimeField> {
|
|||
return;
|
||||
}
|
||||
final String key = field.getName().toLowerCase(Locale.ROOT);
|
||||
List<MimeField> values = this.fieldMap.get(key);
|
||||
if (values == null) {
|
||||
values = new LinkedList<>();
|
||||
this.fieldMap.put(key, values);
|
||||
}
|
||||
final List<MimeField> values = this.fieldMap.computeIfAbsent(key, k -> new LinkedList<>());
|
||||
values.add(field);
|
||||
this.fields.add(field);
|
||||
}
|
||||
|
|
|
@ -54,9 +54,7 @@ public final class IdleConnectionEvictor {
|
|||
Args.notNull(connectionManager, "Connection manager");
|
||||
this.threadFactory = threadFactory != null ? threadFactory : new DefaultThreadFactory("idle-connection-evictor", true);
|
||||
final TimeValue localSleepTime = sleepTime != null ? sleepTime : TimeValue.ofSeconds(5);
|
||||
this.thread = this.threadFactory.newThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
this.thread = this.threadFactory.newThread(() -> {
|
||||
try {
|
||||
while (!Thread.currentThread().isInterrupted()) {
|
||||
localSleepTime.sleep();
|
||||
|
@ -70,7 +68,6 @@ public final class IdleConnectionEvictor {
|
|||
} catch (final Exception ex) {
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -41,14 +41,7 @@ import org.apache.hc.core5.concurrent.Cancellable;
|
|||
*/
|
||||
public final class Operations {
|
||||
|
||||
private final static Cancellable NOOP_CANCELLABLE = new Cancellable() {
|
||||
|
||||
@Override
|
||||
public boolean cancel() {
|
||||
return false;
|
||||
}
|
||||
|
||||
};
|
||||
private final static Cancellable NOOP_CANCELLABLE = () -> false;
|
||||
|
||||
/**
|
||||
* This class represents a {@link Future} in the completed state with a fixed result.
|
||||
|
@ -115,14 +108,7 @@ public final class Operations {
|
|||
if (future instanceof Cancellable) {
|
||||
return (Cancellable) future;
|
||||
}
|
||||
return new Cancellable() {
|
||||
|
||||
@Override
|
||||
public boolean cancel() {
|
||||
return future.cancel(true);
|
||||
}
|
||||
|
||||
};
|
||||
return () -> future.cancel(true);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -66,13 +66,7 @@ abstract class AbstractHttpAsyncClientBase extends CloseableHttpAsyncClient {
|
|||
@Override
|
||||
public final void start() {
|
||||
if (status.compareAndSet(Status.READY, Status.RUNNING)) {
|
||||
executorService.execute(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
ioReactor.start();
|
||||
}
|
||||
});
|
||||
executorService.execute(ioReactor::start);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -51,19 +51,7 @@ class AsyncExecChainElement {
|
|||
final AsyncEntityProducer entityProducer,
|
||||
final AsyncExecChain.Scope scope,
|
||||
final AsyncExecCallback asyncExecCallback) throws HttpException, IOException {
|
||||
handler.execute(request, entityProducer, scope, new AsyncExecChain() {
|
||||
|
||||
@Override
|
||||
public void proceed(
|
||||
final HttpRequest request,
|
||||
final AsyncEntityProducer entityProducer,
|
||||
final AsyncExecChain.Scope scope,
|
||||
final AsyncExecCallback asyncExecCallback) throws HttpException, IOException {
|
||||
next.execute(request, entityProducer, scope, asyncExecCallback);
|
||||
}
|
||||
|
||||
}, asyncExecCallback);
|
||||
|
||||
handler.execute(request, entityProducer, scope, next != null ? next::execute : null, asyncExecCallback);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -29,7 +29,6 @@ package org.apache.hc.client5.http.impl.async;
|
|||
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.security.AccessController;
|
||||
import java.security.PrivilegedAction;
|
||||
import java.util.ArrayList;
|
||||
|
@ -44,8 +43,8 @@ import org.apache.hc.client5.http.HttpRequestRetryStrategy;
|
|||
import org.apache.hc.client5.http.SchemePortResolver;
|
||||
import org.apache.hc.client5.http.async.AsyncExecChainHandler;
|
||||
import org.apache.hc.client5.http.auth.AuthSchemeFactory;
|
||||
import org.apache.hc.client5.http.auth.StandardAuthScheme;
|
||||
import org.apache.hc.client5.http.auth.CredentialsProvider;
|
||||
import org.apache.hc.client5.http.auth.StandardAuthScheme;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.cookie.BasicCookieStore;
|
||||
import org.apache.hc.client5.http.cookie.CookieSpecFactory;
|
||||
|
@ -75,24 +74,16 @@ import org.apache.hc.client5.http.routing.HttpRoutePlanner;
|
|||
import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
|
||||
import org.apache.hc.core5.annotation.Internal;
|
||||
import org.apache.hc.core5.concurrent.DefaultThreadFactory;
|
||||
import org.apache.hc.core5.function.Callback;
|
||||
import org.apache.hc.core5.function.Resolver;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
import org.apache.hc.core5.http.HttpRequest;
|
||||
import org.apache.hc.core5.http.HttpRequestInterceptor;
|
||||
import org.apache.hc.core5.http.HttpResponseInterceptor;
|
||||
import org.apache.hc.core5.http.config.CharCodingConfig;
|
||||
import org.apache.hc.core5.http.config.Lookup;
|
||||
import org.apache.hc.core5.http.config.NamedElementChain;
|
||||
import org.apache.hc.core5.http.config.RegistryBuilder;
|
||||
import org.apache.hc.core5.http.nio.AsyncPushConsumer;
|
||||
import org.apache.hc.core5.http.nio.HandlerFactory;
|
||||
import org.apache.hc.core5.http.nio.command.ShutdownCommand;
|
||||
import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
|
||||
import org.apache.hc.core5.http.protocol.DefaultHttpProcessor;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpProcessor;
|
||||
import org.apache.hc.core5.http.protocol.HttpProcessorBuilder;
|
||||
import org.apache.hc.core5.http.protocol.RequestTargetHost;
|
||||
|
@ -107,7 +98,6 @@ import org.apache.hc.core5.reactor.Command;
|
|||
import org.apache.hc.core5.reactor.DefaultConnectingIOReactor;
|
||||
import org.apache.hc.core5.reactor.IOEventHandlerFactory;
|
||||
import org.apache.hc.core5.reactor.IOReactorConfig;
|
||||
import org.apache.hc.core5.reactor.IOSession;
|
||||
import org.apache.hc.core5.util.Args;
|
||||
import org.apache.hc.core5.util.TimeValue;
|
||||
import org.apache.hc.core5.util.VersionInfo;
|
||||
|
@ -710,14 +700,7 @@ public class H2AsyncClientBuilder {
|
|||
final AsyncPushConsumerRegistry pushConsumerRegistry = new AsyncPushConsumerRegistry();
|
||||
final IOEventHandlerFactory ioEventHandlerFactory = new H2AsyncClientEventHandlerFactory(
|
||||
new DefaultHttpProcessor(new H2RequestContent(), new H2RequestTargetHost(), new H2RequestConnControl()),
|
||||
new HandlerFactory<AsyncPushConsumer>() {
|
||||
|
||||
@Override
|
||||
public AsyncPushConsumer create(final HttpRequest request, final HttpContext context) throws HttpException {
|
||||
return pushConsumerRegistry.get(request);
|
||||
}
|
||||
|
||||
},
|
||||
(request, context) -> pushConsumerRegistry.get(request),
|
||||
h2Config != null ? h2Config : H2Config.DEFAULT,
|
||||
charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT);
|
||||
final DefaultConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(
|
||||
|
@ -727,14 +710,7 @@ public class H2AsyncClientBuilder {
|
|||
LoggingIOSessionDecorator.INSTANCE,
|
||||
LoggingExceptionCallback.INSTANCE,
|
||||
null,
|
||||
new Callback<IOSession>() {
|
||||
|
||||
@Override
|
||||
public void execute(final IOSession ioSession) {
|
||||
ioSession.enqueue(new ShutdownCommand(CloseMode.GRACEFUL), Command.Priority.IMMEDIATE);
|
||||
}
|
||||
|
||||
});
|
||||
ioSession -> ioSession.enqueue(new ShutdownCommand(CloseMode.GRACEFUL), Command.Priority.IMMEDIATE));
|
||||
|
||||
if (execInterceptors != null) {
|
||||
for (final ExecInterceptorEntry entry: execInterceptors) {
|
||||
|
@ -808,14 +784,7 @@ public class H2AsyncClientBuilder {
|
|||
}
|
||||
|
||||
final MultihomeConnectionInitiator connectionInitiator = new MultihomeConnectionInitiator(ioReactor, dnsResolver);
|
||||
final H2ConnPool connPool = new H2ConnPool(connectionInitiator, new Resolver<HttpHost, InetSocketAddress>() {
|
||||
|
||||
@Override
|
||||
public InetSocketAddress resolve(final HttpHost host) {
|
||||
return null;
|
||||
}
|
||||
|
||||
}, tlsStrategyCopy);
|
||||
final H2ConnPool connPool = new H2ConnPool(connectionInitiator, host -> null, tlsStrategyCopy);
|
||||
|
||||
List<Closeable> closeablesCopy = closeables != null ? new ArrayList<>(closeables) : null;
|
||||
if (closeablesCopy == null) {
|
||||
|
@ -824,14 +793,7 @@ public class H2AsyncClientBuilder {
|
|||
if (evictIdleConnections) {
|
||||
final IdleConnectionEvictor connectionEvictor = new IdleConnectionEvictor(connPool,
|
||||
maxIdleTime != null ? maxIdleTime : TimeValue.ofSeconds(30L));
|
||||
closeablesCopy.add(new Closeable() {
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
connectionEvictor.shutdown();
|
||||
}
|
||||
|
||||
});
|
||||
closeablesCopy.add(connectionEvictor::shutdown);
|
||||
connectionEvictor.start();
|
||||
}
|
||||
closeablesCopy.add(connPool);
|
||||
|
@ -852,12 +814,7 @@ public class H2AsyncClientBuilder {
|
|||
}
|
||||
|
||||
private static String getProperty(final String key, final String defaultValue) {
|
||||
return AccessController.doPrivileged(new PrivilegedAction<String>() {
|
||||
@Override
|
||||
public String run() {
|
||||
return System.getProperty(key, defaultValue);
|
||||
}
|
||||
});
|
||||
return AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(key, defaultValue));
|
||||
}
|
||||
|
||||
static class IdleConnectionEvictor implements Closeable {
|
||||
|
@ -865,9 +822,7 @@ public class H2AsyncClientBuilder {
|
|||
private final Thread thread;
|
||||
|
||||
public IdleConnectionEvictor(final H2ConnPool connPool, final TimeValue maxIdleTime) {
|
||||
this.thread = new DefaultThreadFactory("idle-connection-evictor", true).newThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
this.thread = new DefaultThreadFactory("idle-connection-evictor", true).newThread(() -> {
|
||||
try {
|
||||
while (!Thread.currentThread().isInterrupted()) {
|
||||
maxIdleTime.sleep();
|
||||
|
@ -878,7 +833,6 @@ public class H2AsyncClientBuilder {
|
|||
} catch (final Exception ex) {
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
@ -28,7 +28,6 @@
|
|||
package org.apache.hc.client5.http.impl.async;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.net.ProxySelector;
|
||||
import java.security.AccessController;
|
||||
import java.security.PrivilegedAction;
|
||||
|
@ -45,8 +44,8 @@ import org.apache.hc.client5.http.SchemePortResolver;
|
|||
import org.apache.hc.client5.http.UserTokenHandler;
|
||||
import org.apache.hc.client5.http.async.AsyncExecChainHandler;
|
||||
import org.apache.hc.client5.http.auth.AuthSchemeFactory;
|
||||
import org.apache.hc.client5.http.auth.StandardAuthScheme;
|
||||
import org.apache.hc.client5.http.auth.CredentialsProvider;
|
||||
import org.apache.hc.client5.http.auth.StandardAuthScheme;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.cookie.BasicCookieStore;
|
||||
import org.apache.hc.client5.http.cookie.CookieSpecFactory;
|
||||
|
@ -85,11 +84,8 @@ import org.apache.hc.core5.concurrent.DefaultThreadFactory;
|
|||
import org.apache.hc.core5.function.Callback;
|
||||
import org.apache.hc.core5.http.ConnectionReuseStrategy;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
import org.apache.hc.core5.http.HttpRequest;
|
||||
import org.apache.hc.core5.http.HttpRequestInterceptor;
|
||||
import org.apache.hc.core5.http.HttpResponse;
|
||||
import org.apache.hc.core5.http.HttpResponseInterceptor;
|
||||
import org.apache.hc.core5.http.config.CharCodingConfig;
|
||||
import org.apache.hc.core5.http.config.Http1Config;
|
||||
|
@ -97,11 +93,8 @@ import org.apache.hc.core5.http.config.Lookup;
|
|||
import org.apache.hc.core5.http.config.NamedElementChain;
|
||||
import org.apache.hc.core5.http.config.RegistryBuilder;
|
||||
import org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy;
|
||||
import org.apache.hc.core5.http.nio.AsyncPushConsumer;
|
||||
import org.apache.hc.core5.http.nio.HandlerFactory;
|
||||
import org.apache.hc.core5.http.nio.command.ShutdownCommand;
|
||||
import org.apache.hc.core5.http.protocol.DefaultHttpProcessor;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpProcessor;
|
||||
import org.apache.hc.core5.http.protocol.HttpProcessorBuilder;
|
||||
import org.apache.hc.core5.http.protocol.RequestTargetHost;
|
||||
|
@ -117,7 +110,6 @@ import org.apache.hc.core5.reactor.Command;
|
|||
import org.apache.hc.core5.reactor.DefaultConnectingIOReactor;
|
||||
import org.apache.hc.core5.reactor.IOEventHandlerFactory;
|
||||
import org.apache.hc.core5.reactor.IOReactorConfig;
|
||||
import org.apache.hc.core5.reactor.IOSession;
|
||||
import org.apache.hc.core5.util.Args;
|
||||
import org.apache.hc.core5.util.TimeValue;
|
||||
import org.apache.hc.core5.util.VersionInfo;
|
||||
|
@ -857,12 +849,7 @@ public class HttpAsyncClientBuilder {
|
|||
if (proxy != null) {
|
||||
routePlannerCopy = new DefaultProxyRoutePlanner(proxy, schemePortResolverCopy);
|
||||
} else if (systemProperties) {
|
||||
final ProxySelector defaultProxySelector = AccessController.doPrivileged(new PrivilegedAction<ProxySelector>() {
|
||||
@Override
|
||||
public ProxySelector run() {
|
||||
return ProxySelector.getDefault();
|
||||
}
|
||||
});
|
||||
final ProxySelector defaultProxySelector = AccessController.doPrivileged((PrivilegedAction<ProxySelector>) ProxySelector::getDefault);
|
||||
routePlannerCopy = new SystemDefaultRoutePlanner(
|
||||
schemePortResolverCopy, defaultProxySelector);
|
||||
} else {
|
||||
|
@ -890,14 +877,7 @@ public class HttpAsyncClientBuilder {
|
|||
if (connManagerCopy instanceof ConnPoolControl) {
|
||||
final IdleConnectionEvictor connectionEvictor = new IdleConnectionEvictor((ConnPoolControl<?>) connManagerCopy,
|
||||
maxIdleTime, maxIdleTime);
|
||||
closeablesCopy.add(new Closeable() {
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
connectionEvictor.shutdown();
|
||||
}
|
||||
|
||||
});
|
||||
closeablesCopy.add(connectionEvictor::shutdown);
|
||||
connectionEvictor.start();
|
||||
}
|
||||
}
|
||||
|
@ -910,13 +890,7 @@ public class HttpAsyncClientBuilder {
|
|||
if ("true".equalsIgnoreCase(s)) {
|
||||
reuseStrategyCopy = DefaultConnectionReuseStrategy.INSTANCE;
|
||||
} else {
|
||||
reuseStrategyCopy = new ConnectionReuseStrategy() {
|
||||
@Override
|
||||
public boolean keepAlive(
|
||||
final HttpRequest request, final HttpResponse response, final HttpContext context) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
reuseStrategyCopy = (request, response, context) -> false;
|
||||
}
|
||||
} else {
|
||||
reuseStrategyCopy = DefaultConnectionReuseStrategy.INSTANCE;
|
||||
|
@ -925,14 +899,7 @@ public class HttpAsyncClientBuilder {
|
|||
final AsyncPushConsumerRegistry pushConsumerRegistry = new AsyncPushConsumerRegistry();
|
||||
final IOEventHandlerFactory ioEventHandlerFactory = new HttpAsyncClientEventHandlerFactory(
|
||||
new DefaultHttpProcessor(new H2RequestContent(), new H2RequestTargetHost(), new H2RequestConnControl()),
|
||||
new HandlerFactory<AsyncPushConsumer>() {
|
||||
|
||||
@Override
|
||||
public AsyncPushConsumer create(final HttpRequest request, final HttpContext context) throws HttpException {
|
||||
return pushConsumerRegistry.get(request);
|
||||
}
|
||||
|
||||
},
|
||||
(request, context) -> pushConsumerRegistry.get(request),
|
||||
versionPolicy != null ? versionPolicy : HttpVersionPolicy.NEGOTIATE,
|
||||
h2Config != null ? h2Config : H2Config.DEFAULT,
|
||||
h1Config != null ? h1Config : Http1Config.DEFAULT,
|
||||
|
@ -945,14 +912,7 @@ public class HttpAsyncClientBuilder {
|
|||
LoggingIOSessionDecorator.INSTANCE,
|
||||
ioReactorExceptionCallback != null ? ioReactorExceptionCallback : LoggingExceptionCallback.INSTANCE,
|
||||
null,
|
||||
new Callback<IOSession>() {
|
||||
|
||||
@Override
|
||||
public void execute(final IOSession ioSession) {
|
||||
ioSession.enqueue(new ShutdownCommand(CloseMode.GRACEFUL), Command.Priority.IMMEDIATE);
|
||||
}
|
||||
|
||||
});
|
||||
ioSession -> ioSession.enqueue(new ShutdownCommand(CloseMode.GRACEFUL), Command.Priority.IMMEDIATE));
|
||||
|
||||
if (execInterceptors != null) {
|
||||
for (final ExecInterceptorEntry entry: execInterceptors) {
|
||||
|
@ -1033,12 +993,7 @@ public class HttpAsyncClientBuilder {
|
|||
}
|
||||
|
||||
private String getProperty(final String key, final String defaultValue) {
|
||||
return AccessController.doPrivileged(new PrivilegedAction<String>() {
|
||||
@Override
|
||||
public String run() {
|
||||
return System.getProperty(key, defaultValue);
|
||||
}
|
||||
});
|
||||
return AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(key, defaultValue));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -35,16 +35,11 @@ import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBu
|
|||
import org.apache.hc.client5.http.nio.AsyncClientConnectionManager;
|
||||
import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
|
||||
import org.apache.hc.core5.concurrent.DefaultThreadFactory;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.HttpRequest;
|
||||
import org.apache.hc.core5.http.config.CharCodingConfig;
|
||||
import org.apache.hc.core5.http.config.Http1Config;
|
||||
import org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy;
|
||||
import org.apache.hc.core5.http.nio.AsyncPushConsumer;
|
||||
import org.apache.hc.core5.http.nio.HandlerFactory;
|
||||
import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
|
||||
import org.apache.hc.core5.http.protocol.DefaultHttpProcessor;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpProcessor;
|
||||
import org.apache.hc.core5.http.protocol.RequestUserAgent;
|
||||
import org.apache.hc.core5.http2.HttpVersionPolicy;
|
||||
|
@ -157,14 +152,7 @@ public final class HttpAsyncClients {
|
|||
return createMinimalHttpAsyncClientImpl(
|
||||
new HttpAsyncClientEventHandlerFactory(
|
||||
createMinimalProtocolProcessor(),
|
||||
new HandlerFactory<AsyncPushConsumer>() {
|
||||
|
||||
@Override
|
||||
public AsyncPushConsumer create(final HttpRequest request, final HttpContext context) throws HttpException {
|
||||
return pushConsumerRegistry.get(request);
|
||||
}
|
||||
|
||||
},
|
||||
(request, context) -> pushConsumerRegistry.get(request),
|
||||
versionPolicy,
|
||||
h2Config,
|
||||
h1Config,
|
||||
|
@ -252,14 +240,7 @@ public final class HttpAsyncClients {
|
|||
return createMinimalHttp2AsyncClientImpl(
|
||||
new H2AsyncClientEventHandlerFactory(
|
||||
createMinimalProtocolProcessor(),
|
||||
new HandlerFactory<AsyncPushConsumer>() {
|
||||
|
||||
@Override
|
||||
public AsyncPushConsumer create(final HttpRequest request, final HttpContext context) throws HttpException {
|
||||
return pushConsumerRegistry.get(request);
|
||||
}
|
||||
|
||||
},
|
||||
(request, context) -> pushConsumerRegistry.get(request),
|
||||
h2Config,
|
||||
CharCodingConfig.DEFAULT),
|
||||
pushConsumerRegistry,
|
||||
|
|
|
@ -70,7 +70,6 @@ import org.apache.hc.core5.http.nio.AsyncRequestProducer;
|
|||
import org.apache.hc.core5.http.nio.AsyncResponseConsumer;
|
||||
import org.apache.hc.core5.http.nio.DataStreamChannel;
|
||||
import org.apache.hc.core5.http.nio.HandlerFactory;
|
||||
import org.apache.hc.core5.http.nio.RequestChannel;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.apache.hc.core5.http.support.BasicRequestBuilder;
|
||||
import org.apache.hc.core5.io.CloseMode;
|
||||
|
@ -176,13 +175,7 @@ abstract class InternalAbstractHttpAsyncClient extends AbstractHttpAsyncClientBa
|
|||
throw new CancellationException("Request execution cancelled");
|
||||
}
|
||||
final HttpClientContext clientContext = context != null ? HttpClientContext.adapt(context) : HttpClientContext.create();
|
||||
requestProducer.sendRequest(new RequestChannel() {
|
||||
|
||||
@Override
|
||||
public void sendRequest(
|
||||
final HttpRequest request,
|
||||
final EntityDetails entityDetails,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
requestProducer.sendRequest((request, entityDetails, c) -> {
|
||||
|
||||
RequestConfig requestConfig = null;
|
||||
if (request instanceof Configurable) {
|
||||
|
@ -203,18 +196,7 @@ abstract class InternalAbstractHttpAsyncClient extends AbstractHttpAsyncClientBa
|
|||
clientContext.setExchangeId(exchangeId);
|
||||
setupContext(clientContext);
|
||||
|
||||
final AsyncExecChain.Scheduler scheduler = new AsyncExecChain.Scheduler() {
|
||||
|
||||
@Override
|
||||
public void scheduleExecution(final HttpRequest request,
|
||||
final AsyncEntityProducer entityProducer,
|
||||
final AsyncExecChain.Scope scope,
|
||||
final AsyncExecCallback asyncExecCallback,
|
||||
final TimeValue delay) {
|
||||
executeScheduled(request, entityProducer, scope, asyncExecCallback, delay);
|
||||
}
|
||||
|
||||
};
|
||||
final AsyncExecChain.Scheduler scheduler = this::executeScheduled;
|
||||
|
||||
final AsyncExecChain.Scope scope = new AsyncExecChain.Scope(exchangeId, route, request, future,
|
||||
clientContext, execRuntime, scheduler, new AtomicInteger(1));
|
||||
|
@ -289,7 +271,7 @@ abstract class InternalAbstractHttpAsyncClient extends AbstractHttpAsyncClientBa
|
|||
outputTerminated.set(true);
|
||||
requestProducer.releaseResources();
|
||||
}
|
||||
responseConsumer.consumeResponse(response, entityDetails, context,
|
||||
responseConsumer.consumeResponse(response, entityDetails, c,
|
||||
new FutureCallback<T>() {
|
||||
|
||||
@Override
|
||||
|
@ -314,7 +296,7 @@ abstract class InternalAbstractHttpAsyncClient extends AbstractHttpAsyncClientBa
|
|||
@Override
|
||||
public void handleInformationResponse(
|
||||
final HttpResponse response) throws HttpException, IOException {
|
||||
responseConsumer.informationResponse(response, context);
|
||||
responseConsumer.informationResponse(response, c);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -349,8 +331,6 @@ abstract class InternalAbstractHttpAsyncClient extends AbstractHttpAsyncClientBa
|
|||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
}, context);
|
||||
} catch (final HttpException | IOException | IllegalStateException ex) {
|
||||
future.failed(ex);
|
||||
|
|
|
@ -261,12 +261,9 @@ class InternalHttpAsyncExecRuntime implements AsyncExecRuntime {
|
|||
}
|
||||
endpoint.execute(id, exchangeHandler, context);
|
||||
if (context.getRequestConfig().isHardCancellationEnabled()) {
|
||||
return new Cancellable() {
|
||||
@Override
|
||||
public boolean cancel() {
|
||||
return () -> {
|
||||
exchangeHandler.cancel();
|
||||
return true;
|
||||
}
|
||||
};
|
||||
}
|
||||
} else {
|
||||
|
|
|
@ -33,7 +33,6 @@ import java.util.List;
|
|||
import org.apache.hc.core5.http.EntityDetails;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.HttpRequest;
|
||||
import org.apache.hc.core5.http.HttpResponse;
|
||||
import org.apache.hc.core5.http.message.RequestLine;
|
||||
import org.apache.hc.core5.http.message.StatusLine;
|
||||
|
@ -69,20 +68,12 @@ final class LoggingAsyncClientExchangeHandler implements AsyncClientExchangeHand
|
|||
|
||||
@Override
|
||||
public void produceRequest(final RequestChannel channel, final HttpContext context) throws HttpException, IOException {
|
||||
handler.produceRequest(new RequestChannel() {
|
||||
|
||||
@Override
|
||||
public void sendRequest(
|
||||
final HttpRequest request,
|
||||
final EntityDetails entityDetails,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
handler.produceRequest((request, entityDetails, context1) -> {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("{} send request {}, {}", exchangeId, new RequestLine(request),
|
||||
entityDetails != null ? "entity len " + entityDetails.getContentLength() : "null entity");
|
||||
}
|
||||
channel.sendRequest(request, entityDetails, context);
|
||||
}
|
||||
|
||||
channel.sendRequest(request, entityDetails, context1);
|
||||
}, context);
|
||||
}
|
||||
|
||||
|
@ -94,7 +85,7 @@ final class LoggingAsyncClientExchangeHandler implements AsyncClientExchangeHand
|
|||
@Override
|
||||
public void produce(final DataStreamChannel channel) throws IOException {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("{} produce request data", exchangeId);
|
||||
log.debug("{}: produce request data", exchangeId);
|
||||
}
|
||||
handler.produce(new DataStreamChannel() {
|
||||
|
||||
|
@ -106,7 +97,7 @@ final class LoggingAsyncClientExchangeHandler implements AsyncClientExchangeHand
|
|||
@Override
|
||||
public int write(final ByteBuffer src) throws IOException {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("{} produce request data, len {} bytes", exchangeId, src.remaining());
|
||||
log.debug("{}: produce request data, len {} bytes", exchangeId, src.remaining());
|
||||
}
|
||||
return channel.write(src);
|
||||
}
|
||||
|
@ -114,7 +105,7 @@ final class LoggingAsyncClientExchangeHandler implements AsyncClientExchangeHand
|
|||
@Override
|
||||
public void endStream() throws IOException {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("{} end of request data", exchangeId);
|
||||
log.debug("{}: end of request data", exchangeId);
|
||||
}
|
||||
channel.endStream();
|
||||
}
|
||||
|
@ -122,7 +113,7 @@ final class LoggingAsyncClientExchangeHandler implements AsyncClientExchangeHand
|
|||
@Override
|
||||
public void endStream(final List<? extends Header> trailers) throws IOException {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("{} end of request data", exchangeId);
|
||||
log.debug("{}: end of request data", exchangeId);
|
||||
}
|
||||
channel.endStream(trailers);
|
||||
}
|
||||
|
@ -135,7 +126,7 @@ final class LoggingAsyncClientExchangeHandler implements AsyncClientExchangeHand
|
|||
final HttpResponse response,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("{} information response {}", exchangeId, new StatusLine(response));
|
||||
log.debug("{}: information response {}", exchangeId, new StatusLine(response));
|
||||
}
|
||||
handler.consumeInformation(response, context);
|
||||
}
|
||||
|
@ -146,7 +137,7 @@ final class LoggingAsyncClientExchangeHandler implements AsyncClientExchangeHand
|
|||
final EntityDetails entityDetails,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("{} consume response {}, {}", exchangeId, new StatusLine(response), entityDetails != null ? "entity len " + entityDetails.getContentLength() : " null entity");
|
||||
log.debug("{}: consume response {}, {}", exchangeId, new StatusLine(response), entityDetails != null ? "entity len " + entityDetails.getContentLength() : " null entity");
|
||||
}
|
||||
handler.consumeResponse(response, entityDetails, context);
|
||||
}
|
||||
|
@ -154,23 +145,18 @@ final class LoggingAsyncClientExchangeHandler implements AsyncClientExchangeHand
|
|||
|
||||
@Override
|
||||
public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
|
||||
handler.updateCapacity(new CapacityChannel() {
|
||||
|
||||
@Override
|
||||
public void update(final int increment) throws IOException {
|
||||
handler.updateCapacity(increment -> {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("{} capacity update {}", exchangeId, increment);
|
||||
}
|
||||
capacityChannel.update(increment);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void consume(final ByteBuffer src) throws IOException {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("{} consume response data, len {} bytes", exchangeId, src.remaining());
|
||||
log.debug("{}: consume response data, len {} bytes", exchangeId, src.remaining());
|
||||
}
|
||||
handler.consume(src);
|
||||
}
|
||||
|
@ -178,7 +164,7 @@ final class LoggingAsyncClientExchangeHandler implements AsyncClientExchangeHand
|
|||
@Override
|
||||
public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("{} end of response data", exchangeId);
|
||||
log.debug("{}: end of response data", exchangeId);
|
||||
}
|
||||
handler.streamEnd(trailers);
|
||||
}
|
||||
|
@ -186,7 +172,7 @@ final class LoggingAsyncClientExchangeHandler implements AsyncClientExchangeHand
|
|||
@Override
|
||||
public void failed(final Exception cause) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("{} execution failed: {}", exchangeId, cause.getMessage());
|
||||
log.debug("{}: execution failed: {}", exchangeId, cause.getMessage());
|
||||
}
|
||||
handler.failed(cause);
|
||||
}
|
||||
|
@ -194,7 +180,7 @@ final class LoggingAsyncClientExchangeHandler implements AsyncClientExchangeHand
|
|||
@Override
|
||||
public void cancel() {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("{} execution cancelled", exchangeId);
|
||||
log.debug("{}: execution cancelled", exchangeId);
|
||||
}
|
||||
handler.cancel();
|
||||
}
|
||||
|
|
|
@ -27,7 +27,6 @@
|
|||
package org.apache.hc.client5.http.impl.async;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CancellationException;
|
||||
|
@ -47,13 +46,10 @@ import org.apache.hc.core5.annotation.ThreadingBehavior;
|
|||
import org.apache.hc.core5.concurrent.Cancellable;
|
||||
import org.apache.hc.core5.concurrent.ComplexCancellable;
|
||||
import org.apache.hc.core5.concurrent.FutureCallback;
|
||||
import org.apache.hc.core5.function.Callback;
|
||||
import org.apache.hc.core5.function.Resolver;
|
||||
import org.apache.hc.core5.http.EntityDetails;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
import org.apache.hc.core5.http.HttpRequest;
|
||||
import org.apache.hc.core5.http.HttpResponse;
|
||||
import org.apache.hc.core5.http.nio.AsyncClientExchangeHandler;
|
||||
import org.apache.hc.core5.http.nio.AsyncPushConsumer;
|
||||
|
@ -112,25 +108,11 @@ public final class MinimalH2AsyncClient extends AbstractMinimalHttpAsyncClientBa
|
|||
LoggingIOSessionDecorator.INSTANCE,
|
||||
LoggingExceptionCallback.INSTANCE,
|
||||
null,
|
||||
new Callback<IOSession>() {
|
||||
|
||||
@Override
|
||||
public void execute(final IOSession ioSession) {
|
||||
ioSession.enqueue(new ShutdownCommand(CloseMode.GRACEFUL), Command.Priority.IMMEDIATE);
|
||||
}
|
||||
|
||||
}),
|
||||
ioSession -> ioSession.enqueue(new ShutdownCommand(CloseMode.GRACEFUL), Command.Priority.IMMEDIATE)),
|
||||
pushConsumerRegistry,
|
||||
threadFactory);
|
||||
this.connectionInitiator = new MultihomeConnectionInitiator(getConnectionInitiator(), dnsResolver);
|
||||
this.connPool = new H2ConnPool(this.connectionInitiator, new Resolver<HttpHost, InetSocketAddress>() {
|
||||
|
||||
@Override
|
||||
public InetSocketAddress resolve(final HttpHost object) {
|
||||
return null;
|
||||
}
|
||||
|
||||
}, tlsStrategy);
|
||||
this.connPool = new H2ConnPool(this.connectionInitiator, object -> null, tlsStrategy);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -144,13 +126,7 @@ public final class MinimalH2AsyncClient extends AbstractMinimalHttpAsyncClientBa
|
|||
throw new CancellationException("Request execution cancelled");
|
||||
}
|
||||
final HttpClientContext clientContext = context != null ? HttpClientContext.adapt(context) : HttpClientContext.create();
|
||||
exchangeHandler.produceRequest(new RequestChannel() {
|
||||
|
||||
@Override
|
||||
public void sendRequest(
|
||||
final HttpRequest request,
|
||||
final EntityDetails entityDetails,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
exchangeHandler.produceRequest((request, entityDetails, context1) -> {
|
||||
RequestConfig requestConfig = null;
|
||||
if (request instanceof Configurable) {
|
||||
requestConfig = ((Configurable) request).getConfig();
|
||||
|
@ -188,8 +164,8 @@ public final class MinimalH2AsyncClient extends AbstractMinimalHttpAsyncClientBa
|
|||
@Override
|
||||
public void produceRequest(
|
||||
final RequestChannel channel,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
channel.sendRequest(request, entityDetails, context);
|
||||
final HttpContext context1) throws HttpException, IOException {
|
||||
channel.sendRequest(request, entityDetails, context1);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -205,16 +181,16 @@ public final class MinimalH2AsyncClient extends AbstractMinimalHttpAsyncClientBa
|
|||
@Override
|
||||
public void consumeInformation(
|
||||
final HttpResponse response,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
exchangeHandler.consumeInformation(response, context);
|
||||
final HttpContext context1) throws HttpException, IOException {
|
||||
exchangeHandler.consumeInformation(response, context1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void consumeResponse(
|
||||
final HttpResponse response,
|
||||
final EntityDetails entityDetails,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
exchangeHandler.consumeResponse(response, entityDetails, context);
|
||||
final HttpContext context1) throws HttpException, IOException {
|
||||
exchangeHandler.consumeResponse(response, entityDetails, context1);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -265,16 +241,7 @@ public final class MinimalH2AsyncClient extends AbstractMinimalHttpAsyncClientBa
|
|||
}
|
||||
|
||||
});
|
||||
cancellable.setDependency(new Cancellable() {
|
||||
|
||||
@Override
|
||||
public boolean cancel() {
|
||||
return sessionFuture.cancel(true);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
cancellable.setDependency(() -> sessionFuture.cancel(true));
|
||||
}, context);
|
||||
} catch (final HttpException | IOException | IllegalStateException ex) {
|
||||
exchangeHandler.failed(ex);
|
||||
|
|
|
@ -54,12 +54,10 @@ import org.apache.hc.core5.concurrent.Cancellable;
|
|||
import org.apache.hc.core5.concurrent.ComplexCancellable;
|
||||
import org.apache.hc.core5.concurrent.ComplexFuture;
|
||||
import org.apache.hc.core5.concurrent.FutureCallback;
|
||||
import org.apache.hc.core5.function.Callback;
|
||||
import org.apache.hc.core5.http.EntityDetails;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
import org.apache.hc.core5.http.HttpRequest;
|
||||
import org.apache.hc.core5.http.HttpResponse;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.nio.AsyncClientEndpoint;
|
||||
|
@ -78,7 +76,6 @@ import org.apache.hc.core5.reactor.Command;
|
|||
import org.apache.hc.core5.reactor.DefaultConnectingIOReactor;
|
||||
import org.apache.hc.core5.reactor.IOEventHandlerFactory;
|
||||
import org.apache.hc.core5.reactor.IOReactorConfig;
|
||||
import org.apache.hc.core5.reactor.IOSession;
|
||||
import org.apache.hc.core5.util.Args;
|
||||
import org.apache.hc.core5.util.Asserts;
|
||||
import org.apache.hc.core5.util.TimeValue;
|
||||
|
@ -122,14 +119,7 @@ public final class MinimalHttpAsyncClient extends AbstractMinimalHttpAsyncClient
|
|||
LoggingIOSessionDecorator.INSTANCE,
|
||||
LoggingExceptionCallback.INSTANCE,
|
||||
null,
|
||||
new Callback<IOSession>() {
|
||||
|
||||
@Override
|
||||
public void execute(final IOSession ioSession) {
|
||||
ioSession.enqueue(new ShutdownCommand(CloseMode.GRACEFUL), Command.Priority.NORMAL);
|
||||
}
|
||||
|
||||
}),
|
||||
ioSession -> ioSession.enqueue(new ShutdownCommand(CloseMode.GRACEFUL), Command.Priority.NORMAL)),
|
||||
pushConsumerRegistry,
|
||||
threadFactory);
|
||||
this.manager = manager;
|
||||
|
@ -259,13 +249,7 @@ public final class MinimalHttpAsyncClient extends AbstractMinimalHttpAsyncClient
|
|||
throw new CancellationException("Request execution cancelled");
|
||||
}
|
||||
final HttpClientContext clientContext = context != null ? HttpClientContext.adapt(context) : HttpClientContext.create();
|
||||
exchangeHandler.produceRequest(new RequestChannel() {
|
||||
|
||||
@Override
|
||||
public void sendRequest(
|
||||
final HttpRequest request,
|
||||
final EntityDetails entityDetails,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
exchangeHandler.produceRequest((request, entityDetails, context1) -> {
|
||||
RequestConfig requestConfig = null;
|
||||
if (request instanceof Configurable) {
|
||||
requestConfig = ((Configurable) request).getConfig();
|
||||
|
@ -319,8 +303,8 @@ public final class MinimalHttpAsyncClient extends AbstractMinimalHttpAsyncClient
|
|||
@Override
|
||||
public void produceRequest(
|
||||
final RequestChannel channel,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
channel.sendRequest(request, entityDetails, context);
|
||||
final HttpContext context1) throws HttpException, IOException {
|
||||
channel.sendRequest(request, entityDetails, context1);
|
||||
if (entityDetails == null) {
|
||||
messageCountDown.decrementAndGet();
|
||||
}
|
||||
|
@ -367,16 +351,16 @@ public final class MinimalHttpAsyncClient extends AbstractMinimalHttpAsyncClient
|
|||
@Override
|
||||
public void consumeInformation(
|
||||
final HttpResponse response,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
exchangeHandler.consumeInformation(response, context);
|
||||
final HttpContext context1) throws HttpException, IOException {
|
||||
exchangeHandler.consumeInformation(response, context1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void consumeResponse(
|
||||
final HttpResponse response,
|
||||
final EntityDetails entityDetails,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
exchangeHandler.consumeResponse(response, entityDetails, context);
|
||||
final HttpContext context1) throws HttpException, IOException {
|
||||
exchangeHandler.consumeResponse(response, entityDetails, context1);
|
||||
if (response.getCode() >= HttpStatus.SC_CLIENT_ERROR) {
|
||||
messageCountDown.decrementAndGet();
|
||||
}
|
||||
|
@ -424,15 +408,7 @@ public final class MinimalHttpAsyncClient extends AbstractMinimalHttpAsyncClient
|
|||
|
||||
});
|
||||
|
||||
cancellable.setDependency(new Cancellable() {
|
||||
|
||||
@Override
|
||||
public boolean cancel() {
|
||||
return leaseFuture.cancel(true);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
cancellable.setDependency(() -> leaseFuture.cancel(true));
|
||||
}, context);
|
||||
|
||||
} catch (final HttpException | IOException | IllegalStateException ex) {
|
||||
|
|
|
@ -1260,7 +1260,7 @@ final class NTLMEngineImpl implements NTLMEngine {
|
|||
|
||||
Type1Message(final String domain, final String host, final Integer flags) {
|
||||
super();
|
||||
this.flags = ((flags == null)?getDefaultFlags():flags);
|
||||
this.flags = ((flags == null)?getDefaultFlags(): flags.intValue());
|
||||
|
||||
// See HTTPCLIENT-1662
|
||||
final String unqualifiedHost = host;
|
||||
|
|
|
@ -91,11 +91,11 @@ public class AIMDBackoffManager implements BackoffManager {
|
|||
final int curr = connPerRoute.getMaxPerRoute(route);
|
||||
final Long lastUpdate = getLastUpdate(lastRouteBackoffs, route);
|
||||
final long now = clock.getCurrentTime();
|
||||
if (now - lastUpdate.longValue() < coolDown.toMilliseconds()) {
|
||||
if (now - lastUpdate < coolDown.toMilliseconds()) {
|
||||
return;
|
||||
}
|
||||
connPerRoute.setMaxPerRoute(route, getBackedOffPoolSize(curr));
|
||||
lastRouteBackoffs.put(route, Long.valueOf(now));
|
||||
lastRouteBackoffs.put(route, now);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -114,19 +114,19 @@ public class AIMDBackoffManager implements BackoffManager {
|
|||
final Long lastProbe = getLastUpdate(lastRouteProbes, route);
|
||||
final Long lastBackoff = getLastUpdate(lastRouteBackoffs, route);
|
||||
final long now = clock.getCurrentTime();
|
||||
if (now - lastProbe.longValue() < coolDown.toMilliseconds()
|
||||
|| now - lastBackoff.longValue() < coolDown.toMilliseconds()) {
|
||||
if (now - lastProbe < coolDown.toMilliseconds()
|
||||
|| now - lastBackoff < coolDown.toMilliseconds()) {
|
||||
return;
|
||||
}
|
||||
connPerRoute.setMaxPerRoute(route, max);
|
||||
lastRouteProbes.put(route, Long.valueOf(now));
|
||||
lastRouteProbes.put(route, now);
|
||||
}
|
||||
}
|
||||
|
||||
private Long getLastUpdate(final Map<HttpRoute, Long> updates, final HttpRoute route) {
|
||||
Long lastUpdate = updates.get(route);
|
||||
if (lastUpdate == null) {
|
||||
lastUpdate = Long.valueOf(0L);
|
||||
lastUpdate = 0L;
|
||||
}
|
||||
return lastUpdate;
|
||||
}
|
||||
|
|
|
@ -48,16 +48,7 @@ class ExecChainElement {
|
|||
public ClassicHttpResponse execute(
|
||||
final ClassicHttpRequest request,
|
||||
final ExecChain.Scope scope) throws IOException, HttpException {
|
||||
return handler.execute(request, scope, new ExecChain() {
|
||||
|
||||
@Override
|
||||
public ClassicHttpResponse proceed(
|
||||
final ClassicHttpRequest request,
|
||||
final Scope scope) throws IOException, HttpException {
|
||||
return next.execute(request, scope);
|
||||
}
|
||||
|
||||
});
|
||||
return handler.execute(request, scope, next != null ? next::execute : null);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -28,7 +28,6 @@
|
|||
package org.apache.hc.client5.http.impl.classic;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.net.ProxySelector;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
|
@ -43,8 +42,8 @@ import org.apache.hc.client5.http.HttpRequestRetryStrategy;
|
|||
import org.apache.hc.client5.http.SchemePortResolver;
|
||||
import org.apache.hc.client5.http.UserTokenHandler;
|
||||
import org.apache.hc.client5.http.auth.AuthSchemeFactory;
|
||||
import org.apache.hc.client5.http.auth.StandardAuthScheme;
|
||||
import org.apache.hc.client5.http.auth.CredentialsProvider;
|
||||
import org.apache.hc.client5.http.auth.StandardAuthScheme;
|
||||
import org.apache.hc.client5.http.classic.BackoffManager;
|
||||
import org.apache.hc.client5.http.classic.ConnectionBackoffStrategy;
|
||||
import org.apache.hc.client5.http.classic.ExecChainHandler;
|
||||
|
@ -87,9 +86,7 @@ import org.apache.hc.core5.annotation.Internal;
|
|||
import org.apache.hc.core5.http.ConnectionReuseStrategy;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
import org.apache.hc.core5.http.HttpRequest;
|
||||
import org.apache.hc.core5.http.HttpRequestInterceptor;
|
||||
import org.apache.hc.core5.http.HttpResponse;
|
||||
import org.apache.hc.core5.http.HttpResponseInterceptor;
|
||||
import org.apache.hc.core5.http.config.Lookup;
|
||||
import org.apache.hc.core5.http.config.NamedElementChain;
|
||||
|
@ -98,7 +95,6 @@ import org.apache.hc.core5.http.config.RegistryBuilder;
|
|||
import org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy;
|
||||
import org.apache.hc.core5.http.impl.io.HttpRequestExecutor;
|
||||
import org.apache.hc.core5.http.protocol.DefaultHttpProcessor;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpProcessor;
|
||||
import org.apache.hc.core5.http.protocol.HttpProcessorBuilder;
|
||||
import org.apache.hc.core5.http.protocol.RequestContent;
|
||||
|
@ -748,13 +744,7 @@ public class HttpClientBuilder {
|
|||
if ("true".equalsIgnoreCase(s)) {
|
||||
reuseStrategyCopy = DefaultConnectionReuseStrategy.INSTANCE;
|
||||
} else {
|
||||
reuseStrategyCopy = new ConnectionReuseStrategy() {
|
||||
@Override
|
||||
public boolean keepAlive(
|
||||
final HttpRequest request, final HttpResponse response, final HttpContext context) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
reuseStrategyCopy = (request, response, context) -> false;
|
||||
}
|
||||
} else {
|
||||
reuseStrategyCopy = DefaultConnectionReuseStrategy.INSTANCE;
|
||||
|
@ -985,18 +975,13 @@ public class HttpClientBuilder {
|
|||
if (connManagerCopy instanceof ConnPoolControl) {
|
||||
final IdleConnectionEvictor connectionEvictor = new IdleConnectionEvictor((ConnPoolControl<?>) connManagerCopy,
|
||||
maxIdleTime, maxIdleTime);
|
||||
closeablesCopy.add(new Closeable() {
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
closeablesCopy.add(() -> {
|
||||
connectionEvictor.shutdown();
|
||||
try {
|
||||
connectionEvictor.awaitTermination(Timeout.ofSeconds(1));
|
||||
} catch (final InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
connectionEvictor.start();
|
||||
}
|
||||
|
|
|
@ -159,9 +159,7 @@ class ResponseEntityProxy extends HttpEntityWrapper implements EofSensorWatcher
|
|||
public Supplier<List<? extends Header>> getTrailers() {
|
||||
try {
|
||||
final InputStream underlyingStream = super.getContent();
|
||||
return new Supplier<List<? extends Header>>() {
|
||||
@Override
|
||||
public List<? extends Header> get() {
|
||||
return () -> {
|
||||
final Header[] footers;
|
||||
if (underlyingStream instanceof ChunkedInputStream) {
|
||||
final ChunkedInputStream chunkedInputStream = (ChunkedInputStream) underlyingStream;
|
||||
|
@ -170,7 +168,6 @@ class ResponseEntityProxy extends HttpEntityWrapper implements EofSensorWatcher
|
|||
footers = new Header[0];
|
||||
}
|
||||
return Arrays.asList(footers);
|
||||
}
|
||||
};
|
||||
} catch (final IOException e) {
|
||||
throw new IllegalStateException("Unable to retrieve input stream", e);
|
||||
|
|
|
@ -147,7 +147,7 @@ public class LaxExpiresHandler extends AbstractCookieAttributeHandler implements
|
|||
final Matcher matcher = MONTH_PATTERN.matcher(content);
|
||||
if (matcher.matches()) {
|
||||
foundMonth = true;
|
||||
month = MONTHS.get(matcher.group(1).toLowerCase(Locale.ROOT));
|
||||
month = MONTHS.get(matcher.group(1).toLowerCase(Locale.ROOT)).intValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -212,7 +212,7 @@ public class RFC6265CookieSpec implements CookieSpec {
|
|||
if (cookies.size() > 1) {
|
||||
// Create a mutable copy and sort the copy.
|
||||
sortedCookies = new ArrayList<>(cookies);
|
||||
Collections.sort(sortedCookies, CookiePriorityComparator.INSTANCE);
|
||||
sortedCookies.sort(CookiePriorityComparator.INSTANCE);
|
||||
} else {
|
||||
sortedCookies = cookies;
|
||||
}
|
||||
|
|
|
@ -49,7 +49,6 @@ import org.apache.hc.core5.annotation.Internal;
|
|||
import org.apache.hc.core5.annotation.ThreadingBehavior;
|
||||
import org.apache.hc.core5.concurrent.ComplexFuture;
|
||||
import org.apache.hc.core5.concurrent.FutureCallback;
|
||||
import org.apache.hc.core5.function.Callback;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
import org.apache.hc.core5.http.HttpVersion;
|
||||
import org.apache.hc.core5.http.ProtocolVersion;
|
||||
|
@ -250,10 +249,7 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
|
|||
final TimeValue timeValue = PoolingAsyncClientConnectionManager.this.validateAfterInactivity;
|
||||
if (TimeValue.isNonNegative(timeValue) &&
|
||||
poolEntry.getUpdated() + timeValue.toMilliseconds() <= System.currentTimeMillis()) {
|
||||
connection.submitCommand(new PingCommand(new BasicPingHandler(new Callback<Boolean>() {
|
||||
|
||||
@Override
|
||||
public void execute(final Boolean result) {
|
||||
connection.submitCommand(new PingCommand(new BasicPingHandler(result -> {
|
||||
if (result == null || !result) {
|
||||
if (LOG.isDebugEnabled()) {
|
||||
LOG.debug("{} connection {} is stale", id, ConnPoolSupport.getId(connection));
|
||||
|
@ -261,8 +257,6 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
|
|||
poolEntry.discardConnection(CloseMode.IMMEDIATE);
|
||||
}
|
||||
leaseCompleted(poolEntry);
|
||||
}
|
||||
|
||||
})), Command.Priority.IMMEDIATE);
|
||||
return;
|
||||
}
|
||||
|
|
|
@ -81,12 +81,9 @@ public class PlainConnectionSocketFactory implements ConnectionSocketFactory {
|
|||
// Run this under a doPrivileged to support lib users that run under a SecurityManager this allows granting connect permissions
|
||||
// only to this library
|
||||
try {
|
||||
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
|
||||
@Override
|
||||
public Object run() throws IOException {
|
||||
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
|
||||
sock.connect(remoteAddress, TimeValue.isPositive(connectTimeout) ? connectTimeout.toMillisecondsIntBound() : 0);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
} catch (final PrivilegedActionException e) {
|
||||
Asserts.check(e.getCause() instanceof IOException,
|
||||
|
|
|
@ -47,10 +47,7 @@ import org.apache.hc.core5.http.ssl.TlsCiphers;
|
|||
import org.apache.hc.core5.http2.HttpVersionPolicy;
|
||||
import org.apache.hc.core5.http2.ssl.ApplicationProtocol;
|
||||
import org.apache.hc.core5.http2.ssl.H2TlsSupport;
|
||||
import org.apache.hc.core5.net.NamedEndpoint;
|
||||
import org.apache.hc.core5.reactor.ssl.SSLBufferMode;
|
||||
import org.apache.hc.core5.reactor.ssl.SSLSessionInitializer;
|
||||
import org.apache.hc.core5.reactor.ssl.SSLSessionVerifier;
|
||||
import org.apache.hc.core5.reactor.ssl.TlsDetails;
|
||||
import org.apache.hc.core5.reactor.ssl.TransportSecurityLayer;
|
||||
import org.apache.hc.core5.util.Args;
|
||||
|
@ -93,10 +90,7 @@ abstract class AbstractClientTlsStrategy implements TlsStrategy {
|
|||
final SocketAddress remoteAddress,
|
||||
final Object attachment,
|
||||
final Timeout handshakeTimeout) {
|
||||
tlsSession.startTls(sslContext, host, sslBufferManagement, new SSLSessionInitializer() {
|
||||
|
||||
@Override
|
||||
public void initialize(final NamedEndpoint endpoint, final SSLEngine sslEngine) {
|
||||
tlsSession.startTls(sslContext, host, sslBufferManagement, (endpoint, sslEngine) -> {
|
||||
|
||||
final HttpVersionPolicy versionPolicy = attachment instanceof HttpVersionPolicy ?
|
||||
(HttpVersionPolicy) attachment : HttpVersionPolicy.NEGOTIATE;
|
||||
|
@ -125,12 +119,7 @@ abstract class AbstractClientTlsStrategy implements TlsStrategy {
|
|||
LOG.debug("Enabled protocols: {}", Arrays.asList(sslEngine.getEnabledProtocols()));
|
||||
LOG.debug("Enabled cipher suites:{}", Arrays.asList(sslEngine.getEnabledCipherSuites()));
|
||||
}
|
||||
}
|
||||
|
||||
}, new SSLSessionVerifier() {
|
||||
|
||||
@Override
|
||||
public TlsDetails verify(final NamedEndpoint endpoint, final SSLEngine sslEngine) throws SSLException {
|
||||
}, (endpoint, sslEngine) -> {
|
||||
verifySession(host.getHostName(), sslEngine.getSession());
|
||||
final TlsDetails tlsDetails = createTlsDetails(sslEngine);
|
||||
final String negotiatedCipherSuite = sslEngine.getSession().getCipherSuite();
|
||||
|
@ -141,8 +130,6 @@ abstract class AbstractClientTlsStrategy implements TlsStrategy {
|
|||
}
|
||||
}
|
||||
return tlsDetails;
|
||||
}
|
||||
|
||||
}, handshakeTimeout);
|
||||
return true;
|
||||
}
|
||||
|
|
|
@ -171,14 +171,11 @@ public class ClientTlsStrategyBuilder {
|
|||
if (tlsDetailsFactory != null) {
|
||||
tlsDetailsFactoryCopy = tlsDetailsFactory;
|
||||
} else {
|
||||
tlsDetailsFactoryCopy = new Factory<SSLEngine, TlsDetails>() {
|
||||
@Override
|
||||
public TlsDetails create(final SSLEngine sslEngine) {
|
||||
tlsDetailsFactoryCopy = sslEngine -> {
|
||||
final SSLSession sslSession = sslEngine.getSession();
|
||||
final String applicationProtocol = ReflectionUtils.callGetter(sslEngine,
|
||||
"ApplicationProtocol", String.class);
|
||||
return new TlsDetails(sslSession, applicationProtocol);
|
||||
}
|
||||
};
|
||||
}
|
||||
return new DefaultClientTlsStrategy(
|
||||
|
|
|
@ -109,7 +109,7 @@ public class ConscryptClientTlsStrategy extends AbstractClientTlsStrategy {
|
|||
try {
|
||||
final Class<?> clazz = Class.forName("org.conscrypt.Conscrypt");
|
||||
final Method method = clazz.getMethod("isAvailable");
|
||||
return (Boolean) method.invoke(null);
|
||||
return ((Boolean) method.invoke(null)).booleanValue();
|
||||
} catch (final ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
|
||||
return false;
|
||||
}
|
||||
|
|
|
@ -50,14 +50,7 @@ public final class HttpsSupport {
|
|||
}
|
||||
|
||||
private static String getProperty(final String key) {
|
||||
return AccessController.doPrivileged(new PrivilegedAction<String>() {
|
||||
|
||||
@Override
|
||||
public String run() {
|
||||
return System.getProperty(key);
|
||||
}
|
||||
|
||||
});
|
||||
return AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(key));
|
||||
}
|
||||
|
||||
public static String[] getSystemProtocols() {
|
||||
|
|
|
@ -213,12 +213,9 @@ public class SSLConnectionSocketFactory implements LayeredConnectionSocketFactor
|
|||
// Run this under a doPrivileged to support lib users that run under a SecurityManager this allows granting connect permissions
|
||||
// only to this library
|
||||
try {
|
||||
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
|
||||
@Override
|
||||
public Object run() throws IOException {
|
||||
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
|
||||
sock.connect(remoteAddress, connectTimeout != null ? connectTimeout.toMillisecondsIntBound() : 0);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
} catch (final PrivilegedActionException e) {
|
||||
Asserts.check(e.getCause() instanceof IOException,
|
||||
|
|
|
@ -29,7 +29,6 @@ package org.apache.hc.client5.http.entity;
|
|||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.zip.CRC32;
|
||||
|
@ -95,14 +94,7 @@ public class TestDecompressingEntity {
|
|||
static class ChecksumEntity extends DecompressingEntity {
|
||||
|
||||
public ChecksumEntity(final HttpEntity wrapped, final Checksum checksum) {
|
||||
super(wrapped, new InputStreamFactory() {
|
||||
|
||||
@Override
|
||||
public InputStream create(final InputStream inStream) throws IOException {
|
||||
return new CheckedInputStream(inStream, checksum);
|
||||
}
|
||||
|
||||
});
|
||||
super(wrapped, inStream -> new CheckedInputStream(inStream, checksum));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -26,7 +26,6 @@
|
|||
*/
|
||||
package org.apache.hc.client5.http.examples;
|
||||
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
|
@ -50,7 +49,6 @@ import org.apache.hc.core5.http.message.StatusLine;
|
|||
import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
|
||||
import org.apache.hc.core5.io.CloseMode;
|
||||
import org.apache.hc.core5.ssl.SSLContexts;
|
||||
import org.apache.hc.core5.ssl.TrustStrategy;
|
||||
|
||||
/**
|
||||
* This example demonstrates how to create secure connections with a custom SSL
|
||||
|
@ -61,16 +59,9 @@ public class AsyncClientCustomSSL {
|
|||
public static void main(final String[] args) throws Exception {
|
||||
// Trust standard CA and those trusted by our custom strategy
|
||||
final SSLContext sslcontext = SSLContexts.custom()
|
||||
.loadTrustMaterial(new TrustStrategy() {
|
||||
|
||||
@Override
|
||||
public boolean isTrusted(
|
||||
final X509Certificate[] chain,
|
||||
final String authType) throws CertificateException {
|
||||
.loadTrustMaterial((chain, authType) -> {
|
||||
final X509Certificate cert = chain[0];
|
||||
return "CN=httpbin.org".equalsIgnoreCase(cert.getSubjectDN().getName());
|
||||
}
|
||||
|
||||
})
|
||||
.build();
|
||||
final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create()
|
||||
|
|
|
@ -35,14 +35,12 @@ import org.apache.hc.client5.http.async.methods.AbstractBinPushConsumer;
|
|||
import org.apache.hc.client5.http.async.methods.AbstractCharResponseConsumer;
|
||||
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
|
||||
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
|
||||
import org.apache.hc.core5.function.Supplier;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.HttpRequest;
|
||||
import org.apache.hc.core5.http.HttpResponse;
|
||||
import org.apache.hc.core5.http.message.BasicHttpRequest;
|
||||
import org.apache.hc.core5.http.message.StatusLine;
|
||||
import org.apache.hc.core5.http.nio.AsyncPushConsumer;
|
||||
import org.apache.hc.core5.http.nio.support.BasicRequestProducer;
|
||||
import org.apache.hc.core5.http.support.BasicRequestBuilder;
|
||||
import org.apache.hc.core5.http2.HttpVersionPolicy;
|
||||
|
@ -74,11 +72,7 @@ public class AsyncClientH2ServerPush {
|
|||
|
||||
client.start();
|
||||
|
||||
client.register("*", new Supplier<AsyncPushConsumer>() {
|
||||
|
||||
@Override
|
||||
public AsyncPushConsumer get() {
|
||||
return new AbstractBinPushConsumer() {
|
||||
client.register("*", () -> new AbstractBinPushConsumer() {
|
||||
|
||||
@Override
|
||||
protected void start(
|
||||
|
@ -110,9 +104,6 @@ public class AsyncClientH2ServerPush {
|
|||
public void releaseResources() {
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
final BasicHttpRequest request = BasicRequestBuilder.get("https://nghttp2.org/httpbin/").build();
|
||||
|
|
|
@ -33,9 +33,6 @@ import java.nio.charset.StandardCharsets;
|
|||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import org.apache.hc.client5.http.async.AsyncExecCallback;
|
||||
import org.apache.hc.client5.http.async.AsyncExecChain;
|
||||
import org.apache.hc.client5.http.async.AsyncExecChainHandler;
|
||||
import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
|
||||
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
|
||||
import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
|
||||
|
@ -55,7 +52,6 @@ import org.apache.hc.core5.http.impl.BasicEntityDetails;
|
|||
import org.apache.hc.core5.http.message.BasicHttpResponse;
|
||||
import org.apache.hc.core5.http.message.StatusLine;
|
||||
import org.apache.hc.core5.http.nio.AsyncDataConsumer;
|
||||
import org.apache.hc.core5.http.nio.AsyncEntityProducer;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.apache.hc.core5.io.CloseMode;
|
||||
import org.apache.hc.core5.reactor.IOReactorConfig;
|
||||
|
@ -93,15 +89,7 @@ public class AsyncClientInterceptors {
|
|||
|
||||
// Simulate a 404 response for some requests without passing the message down to the backend
|
||||
|
||||
.addExecInterceptorAfter(ChainElement.PROTOCOL.name(), "custom", new AsyncExecChainHandler() {
|
||||
|
||||
@Override
|
||||
public void execute(
|
||||
final HttpRequest request,
|
||||
final AsyncEntityProducer requestEntityProducer,
|
||||
final AsyncExecChain.Scope scope,
|
||||
final AsyncExecChain chain,
|
||||
final AsyncExecCallback asyncExecCallback) throws HttpException, IOException {
|
||||
.addExecInterceptorAfter(ChainElement.PROTOCOL.name(), "custom", (request, requestEntityProducer, scope, chain, asyncExecCallback) -> {
|
||||
final Header idHeader = request.getFirstHeader("request-id");
|
||||
if (idHeader != null && "13".equalsIgnoreCase(idHeader.getValue())) {
|
||||
final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_NOT_FOUND, "Oppsie");
|
||||
|
@ -114,8 +102,6 @@ public class AsyncClientInterceptors {
|
|||
} else {
|
||||
chain.proceed(request, requestEntityProducer, scope, asyncExecCallback);
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
.build();
|
||||
|
|
|
@ -27,12 +27,8 @@
|
|||
|
||||
package org.apache.hc.client5.http.examples;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import org.apache.hc.client5.http.async.AsyncExecCallback;
|
||||
import org.apache.hc.client5.http.async.AsyncExecChain;
|
||||
import org.apache.hc.client5.http.async.AsyncExecChainHandler;
|
||||
import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
|
||||
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
|
||||
import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
|
||||
|
@ -43,10 +39,7 @@ import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
|
|||
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
|
||||
import org.apache.hc.core5.concurrent.FutureCallback;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.HttpRequest;
|
||||
import org.apache.hc.core5.http.message.StatusLine;
|
||||
import org.apache.hc.core5.http.nio.AsyncEntityProducer;
|
||||
import org.apache.hc.core5.http.nio.entity.DigestingEntityProducer;
|
||||
import org.apache.hc.core5.io.CloseMode;
|
||||
import org.apache.hc.core5.reactor.IOReactorConfig;
|
||||
|
@ -66,23 +59,13 @@ public class AsyncClientMessageTrailers {
|
|||
|
||||
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
|
||||
.setIOReactorConfig(ioReactorConfig)
|
||||
.addExecInterceptorAfter(ChainElement.PROTOCOL.name(), "custom", new AsyncExecChainHandler() {
|
||||
|
||||
@Override
|
||||
public void execute(
|
||||
final HttpRequest request,
|
||||
final AsyncEntityProducer entityProducer,
|
||||
final AsyncExecChain.Scope scope,
|
||||
final AsyncExecChain chain,
|
||||
final AsyncExecCallback asyncExecCallback) throws HttpException, IOException {
|
||||
.addExecInterceptorAfter(ChainElement.PROTOCOL.name(), "custom", (request, entityProducer, scope, chain, asyncExecCallback) -> {
|
||||
// Send MD5 hash in a trailer by decorating the original entity producer
|
||||
chain.proceed(
|
||||
request,
|
||||
entityProducer != null ? new DigestingEntityProducer("MD5", entityProducer) : null,
|
||||
scope,
|
||||
asyncExecCallback);
|
||||
}
|
||||
|
||||
})
|
||||
.build();
|
||||
|
||||
|
|
|
@ -26,7 +26,6 @@
|
|||
*/
|
||||
package org.apache.hc.client5.http.examples;
|
||||
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
|
@ -44,7 +43,6 @@ import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
|
|||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.ssl.TLS;
|
||||
import org.apache.hc.core5.ssl.SSLContexts;
|
||||
import org.apache.hc.core5.ssl.TrustStrategy;
|
||||
|
||||
/**
|
||||
* This example demonstrates how to create secure connections with a custom SSL
|
||||
|
@ -55,16 +53,9 @@ public class ClientCustomSSL {
|
|||
public final static void main(final String[] args) throws Exception {
|
||||
// Trust standard CA and those trusted by our custom strategy
|
||||
final SSLContext sslcontext = SSLContexts.custom()
|
||||
.loadTrustMaterial(new TrustStrategy() {
|
||||
|
||||
@Override
|
||||
public boolean isTrusted(
|
||||
final X509Certificate[] chain,
|
||||
final String authType) throws CertificateException {
|
||||
.loadTrustMaterial((chain, authType) -> {
|
||||
final X509Certificate cert = chain[0];
|
||||
return "CN=httpbin.org".equalsIgnoreCase(cert.getSubjectDN().getName());
|
||||
}
|
||||
|
||||
})
|
||||
.build();
|
||||
// Allow TLSv1.2 protocol only
|
||||
|
|
|
@ -30,14 +30,11 @@ package org.apache.hc.client5.http.examples;
|
|||
import java.io.IOException;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import org.apache.hc.client5.http.classic.ExecChain;
|
||||
import org.apache.hc.client5.http.classic.ExecChainHandler;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.impl.ChainElement;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.EntityDetails;
|
||||
|
@ -77,13 +74,7 @@ public class ClientInterceptors {
|
|||
|
||||
// Simulate a 404 response for some requests without passing the message down to the backend
|
||||
|
||||
.addExecInterceptorAfter(ChainElement.PROTOCOL.name(), "custom", new ExecChainHandler() {
|
||||
|
||||
@Override
|
||||
public ClassicHttpResponse execute(
|
||||
final ClassicHttpRequest request,
|
||||
final ExecChain.Scope scope,
|
||||
final ExecChain chain) throws IOException, HttpException {
|
||||
.addExecInterceptorAfter(ChainElement.PROTOCOL.name(), "custom", (request, scope, chain) -> {
|
||||
|
||||
final Header idHeader = request.getFirstHeader("request-id");
|
||||
if (idHeader != null && "13".equalsIgnoreCase(idHeader.getValue())) {
|
||||
|
@ -93,8 +84,6 @@ public class ClientInterceptors {
|
|||
} else {
|
||||
return chain.proceed(request, scope);
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
.build()) {
|
||||
|
||||
|
|
|
@ -26,7 +26,6 @@
|
|||
*/
|
||||
package org.apache.hc.client5.http.examples;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
@ -41,7 +40,6 @@ import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuil
|
|||
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
|
||||
import org.apache.hc.client5.http.protocol.HttpClientContext;
|
||||
import org.apache.hc.core5.concurrent.FutureCallback;
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
|
||||
|
||||
|
@ -60,12 +58,9 @@ public class ClientWithRequestFuture {
|
|||
try (final FutureRequestExecutionService requestExecService = new FutureRequestExecutionService(
|
||||
httpclient, execService)) {
|
||||
// Because things are asynchronous, you must provide a HttpClientResponseHandler
|
||||
final HttpClientResponseHandler<Boolean> handler = new HttpClientResponseHandler<Boolean>() {
|
||||
@Override
|
||||
public Boolean handleResponse(final ClassicHttpResponse response) throws IOException {
|
||||
final HttpClientResponseHandler<Boolean> handler = response -> {
|
||||
// simply return true if the status was OK
|
||||
return response.getCode() == HttpStatus.SC_OK;
|
||||
}
|
||||
};
|
||||
|
||||
// Simple request ...
|
||||
|
|
|
@ -27,13 +27,10 @@
|
|||
|
||||
package org.apache.hc.client5.http.examples;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.hc.client5.http.ClientProtocolException;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
import org.apache.hc.core5.http.HttpEntity;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.ParseException;
|
||||
|
@ -53,11 +50,7 @@ public class ClientWithResponseHandler {
|
|||
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
|
||||
|
||||
// Create a custom response handler
|
||||
final HttpClientResponseHandler<String> responseHandler = new HttpClientResponseHandler<String>() {
|
||||
|
||||
@Override
|
||||
public String handleResponse(
|
||||
final ClassicHttpResponse response) throws IOException {
|
||||
final HttpClientResponseHandler<String> responseHandler = response -> {
|
||||
final int status = response.getCode();
|
||||
if (status >= HttpStatus.SC_SUCCESS && status < HttpStatus.SC_REDIRECTION) {
|
||||
final HttpEntity entity = response.getEntity();
|
||||
|
@ -69,8 +62,6 @@ public class ClientWithResponseHandler {
|
|||
} else {
|
||||
throw new ClientProtocolException("Unexpected response status: " + status);
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
final String responseBody = httpclient.execute(httpget, responseHandler);
|
||||
System.out.println("----------------------------------------");
|
||||
|
|
|
@ -50,10 +50,7 @@ import org.apache.hc.core5.util.Timeout;
|
|||
import org.reactivestreams.Publisher;
|
||||
|
||||
import io.reactivex.Flowable;
|
||||
import io.reactivex.Notification;
|
||||
import io.reactivex.Observable;
|
||||
import io.reactivex.functions.Consumer;
|
||||
import io.reactivex.functions.Function;
|
||||
|
||||
/**
|
||||
* This example demonstrates a reactive, full-duplex HTTP/1.1 message exchange using RxJava.
|
||||
|
@ -92,21 +89,13 @@ public class ReactiveClientFullDuplexExchange {
|
|||
System.out.println();
|
||||
|
||||
Observable.fromPublisher(streamingResponse.getBody())
|
||||
.map(new Function<ByteBuffer, String>() {
|
||||
@Override
|
||||
public String apply(final ByteBuffer byteBuffer) throws Exception {
|
||||
.map(byteBuffer -> {
|
||||
final byte[] string = new byte[byteBuffer.remaining()];
|
||||
byteBuffer.get(string);
|
||||
return new String(string);
|
||||
}
|
||||
})
|
||||
.materialize()
|
||||
.forEach(new Consumer<Notification<String>>() {
|
||||
@Override
|
||||
public void accept(final Notification<String> byteBufferNotification) throws Exception {
|
||||
System.out.println(byteBufferNotification);
|
||||
}
|
||||
});
|
||||
.forEach(System.out::println);
|
||||
|
||||
requestFuture.get(1, TimeUnit.MINUTES);
|
||||
|
||||
|
|
|
@ -82,14 +82,14 @@ public final class MockConnPoolControl implements ConnPoolControl<HttpRoute> {
|
|||
|
||||
@Override
|
||||
public void setMaxPerRoute(final HttpRoute route, final int max) {
|
||||
this.maxPerHostMap.put(route, Integer.valueOf(max));
|
||||
this.maxPerHostMap.put(route, max);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMaxPerRoute(final HttpRoute route) {
|
||||
final Integer max = this.maxPerHostMap.get(route);
|
||||
if (max != null) {
|
||||
return max.intValue();
|
||||
return max;
|
||||
} else {
|
||||
return this.defaultMax;
|
||||
}
|
||||
|
|
|
@ -36,9 +36,9 @@ import org.apache.hc.client5.http.HttpRoute;
|
|||
import org.apache.hc.client5.http.RouteInfo;
|
||||
import org.apache.hc.client5.http.auth.AuthChallenge;
|
||||
import org.apache.hc.client5.http.auth.AuthScheme;
|
||||
import org.apache.hc.client5.http.auth.StandardAuthScheme;
|
||||
import org.apache.hc.client5.http.auth.AuthScope;
|
||||
import org.apache.hc.client5.http.auth.ChallengeType;
|
||||
import org.apache.hc.client5.http.auth.StandardAuthScheme;
|
||||
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.hc.client5.http.classic.ExecChain;
|
||||
import org.apache.hc.client5.http.classic.ExecRuntime;
|
||||
|
@ -67,7 +67,6 @@ import org.mockito.ArgumentCaptor;
|
|||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
@SuppressWarnings({"boxing","static-access"}) // test code
|
||||
|
@ -343,29 +342,17 @@ public class TestConnectExec {
|
|||
|
||||
private boolean connected;
|
||||
|
||||
public Answer connectAnswer() {
|
||||
public Answer<?> connectAnswer() {
|
||||
|
||||
return new Answer() {
|
||||
|
||||
@Override
|
||||
public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
|
||||
return invocationOnMock -> {
|
||||
connected = true;
|
||||
return null;
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
public Answer<Boolean> isConnectedAnswer() {
|
||||
|
||||
return new Answer<Boolean>() {
|
||||
|
||||
@Override
|
||||
public Boolean answer(final InvocationOnMock invocationOnMock) throws Throwable {
|
||||
return connected;
|
||||
}
|
||||
|
||||
};
|
||||
return invocationOnMock -> connected;
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -45,14 +45,10 @@ import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuil
|
|||
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
|
||||
import org.apache.hc.client5.http.protocol.HttpClientContext;
|
||||
import org.apache.hc.core5.concurrent.FutureCallback;
|
||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.impl.bootstrap.HttpServer;
|
||||
import org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap;
|
||||
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
|
||||
import org.apache.hc.core5.http.io.HttpRequestHandler;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
|
@ -76,13 +72,7 @@ public class TestFutureRequestExecutionService {
|
|||
@Before
|
||||
public void before() throws Exception {
|
||||
this.localServer = ServerBootstrap.bootstrap()
|
||||
.register("/wait", new HttpRequestHandler() {
|
||||
|
||||
@Override
|
||||
public void handle(
|
||||
final ClassicHttpRequest request,
|
||||
final ClassicHttpResponse response,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
.register("/wait", (request, response, context) -> {
|
||||
try {
|
||||
while(blocked.get()) {
|
||||
Thread.sleep(10);
|
||||
|
@ -91,7 +81,6 @@ public class TestFutureRequestExecutionService {
|
|||
throw new IllegalStateException(e);
|
||||
}
|
||||
response.setCode(200);
|
||||
}
|
||||
}).create();
|
||||
|
||||
this.localServer.start();
|
||||
|
@ -117,7 +106,7 @@ public class TestFutureRequestExecutionService {
|
|||
public void shouldExecuteSingleCall() throws InterruptedException, ExecutionException {
|
||||
final FutureTask<Boolean> task = httpAsyncClientWithFuture.execute(
|
||||
new HttpGet(uri), HttpClientContext.create(), new OkidokiHandler());
|
||||
Assert.assertTrue("request should have returned OK", task.get().booleanValue());
|
||||
Assert.assertTrue("request should have returned OK", task.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -154,7 +143,7 @@ public class TestFutureRequestExecutionService {
|
|||
for (final Future<Boolean> task : tasks) {
|
||||
final Boolean b = task.get();
|
||||
Assert.assertNotNull(b);
|
||||
Assert.assertTrue("request should have returned OK", b.booleanValue());
|
||||
Assert.assertTrue("request should have returned OK", b);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -173,7 +162,7 @@ public class TestFutureRequestExecutionService {
|
|||
for (final Future<Boolean> task : tasks) {
|
||||
final Boolean b = task.get();
|
||||
Assert.assertNotNull(b);
|
||||
Assert.assertTrue("request should have returned OK", b.booleanValue());
|
||||
Assert.assertTrue("request should have returned OK", b);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -28,9 +28,6 @@ package org.apache.hc.client5.http.impl.classic;
|
|||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.hc.client5.http.classic.ExecChain;
|
||||
import org.apache.hc.client5.http.classic.ExecChainHandler;
|
||||
import org.apache.hc.client5.http.classic.ExecChain.Scope;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
|
||||
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
|
||||
|
@ -40,8 +37,6 @@ import org.apache.hc.core5.http.Header;
|
|||
import org.apache.hc.core5.http.HttpException;
|
||||
import org.apache.hc.core5.http.impl.bootstrap.HttpServer;
|
||||
import org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap;
|
||||
import org.apache.hc.core5.http.io.HttpRequestHandler;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.apache.hc.core5.io.CloseMode;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
|
@ -58,19 +53,12 @@ public class TestHttpClientBuilderInterceptors {
|
|||
@Before
|
||||
public void before() throws Exception {
|
||||
this.localServer = ServerBootstrap.bootstrap()
|
||||
.register("/test", new HttpRequestHandler() {
|
||||
|
||||
@Override
|
||||
public void handle(
|
||||
final ClassicHttpRequest request,
|
||||
final ClassicHttpResponse response,
|
||||
final HttpContext context) throws HttpException, IOException {
|
||||
.register("/test", (request, response, context) -> {
|
||||
final Header testInterceptorHeader = request.getHeader("X-Test-Interceptor");
|
||||
if (testInterceptorHeader != null) {
|
||||
response.setHeader(testInterceptorHeader);
|
||||
}
|
||||
response.setCode(200);
|
||||
}
|
||||
}).create();
|
||||
|
||||
this.localServer.start();
|
||||
|
@ -80,16 +68,9 @@ public class TestHttpClientBuilderInterceptors {
|
|||
.build();
|
||||
httpClient = HttpClientBuilder.create()
|
||||
.setConnectionManager(cm)
|
||||
.addExecInterceptorLast("test-interceptor", new ExecChainHandler() {
|
||||
|
||||
@Override
|
||||
public ClassicHttpResponse execute(
|
||||
final ClassicHttpRequest request,
|
||||
final Scope scope,
|
||||
final ExecChain chain) throws IOException, HttpException {
|
||||
.addExecInterceptorLast("test-interceptor", (request, scope, chain) -> {
|
||||
request.setHeader("X-Test-Interceptor", "active");
|
||||
return chain.proceed(request, scope);
|
||||
}
|
||||
})
|
||||
.build();
|
||||
}
|
||||
|
|
|
@ -55,8 +55,6 @@ import org.junit.Test;
|
|||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
@SuppressWarnings({"boxing","static-access"}) // test code
|
||||
public class TestHttpRequestRetryExec {
|
||||
|
@ -231,10 +229,7 @@ public class TestHttpRequestRetryExec {
|
|||
|
||||
Mockito.when(chain.proceed(
|
||||
Mockito.<ClassicHttpRequest>any(),
|
||||
Mockito.<ExecChain.Scope>any())).thenAnswer(new Answer<Object>() {
|
||||
|
||||
@Override
|
||||
public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
|
||||
Mockito.<ExecChain.Scope>any())).thenAnswer(invocationOnMock -> {
|
||||
final Object[] args = invocationOnMock.getArguments();
|
||||
final ClassicHttpRequest wrapper = (ClassicHttpRequest) args[0];
|
||||
final Header[] headers = wrapper.getHeaders();
|
||||
|
@ -243,8 +238,6 @@ public class TestHttpRequestRetryExec {
|
|||
Assert.assertEquals("that", headers[1].getValue());
|
||||
wrapper.addHeader("Cookie", "monster");
|
||||
throw new IOException("Ka-boom");
|
||||
}
|
||||
|
||||
});
|
||||
Mockito.when(retryStrategy.retryRequest(
|
||||
Mockito.<HttpRequest>any(),
|
||||
|
@ -304,16 +297,11 @@ public class TestHttpRequestRetryExec {
|
|||
|
||||
Mockito.when(chain.proceed(
|
||||
Mockito.<ClassicHttpRequest>any(),
|
||||
Mockito.<ExecChain.Scope>any())).thenAnswer(new Answer<Object>() {
|
||||
|
||||
@Override
|
||||
public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
|
||||
Mockito.<ExecChain.Scope>any())).thenAnswer(invocationOnMock -> {
|
||||
final Object[] args = invocationOnMock.getArguments();
|
||||
final ClassicHttpRequest req = (ClassicHttpRequest) args[0];
|
||||
req.getEntity().writeTo(new ByteArrayOutputStream());
|
||||
throw new IOException("Ka-boom");
|
||||
}
|
||||
|
||||
});
|
||||
Mockito.when(retryStrategy.retryRequest(
|
||||
Mockito.<HttpRequest>any(),
|
||||
|
|
|
@ -53,7 +53,6 @@ import org.junit.Test;
|
|||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
@SuppressWarnings({"boxing","static-access"}) // test code
|
||||
|
@ -330,29 +329,17 @@ public class TestMainClientExec {
|
|||
|
||||
private boolean connected;
|
||||
|
||||
public Answer connectAnswer() {
|
||||
public Answer<?> connectAnswer() {
|
||||
|
||||
return new Answer() {
|
||||
|
||||
@Override
|
||||
public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
|
||||
return invocationOnMock -> {
|
||||
connected = true;
|
||||
return null;
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
public Answer<Boolean> isConnectedAnswer() {
|
||||
|
||||
return new Answer<Boolean>() {
|
||||
|
||||
@Override
|
||||
public Boolean answer(final InvocationOnMock invocationOnMock) throws Throwable {
|
||||
return connected;
|
||||
}
|
||||
|
||||
};
|
||||
return invocationOnMock -> connected;
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -70,7 +70,6 @@ import org.junit.Test;
|
|||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
@SuppressWarnings({"static-access"}) // test code
|
||||
|
@ -317,16 +316,11 @@ public class TestProtocolExec {
|
|||
|
||||
Mockito.when(chain.proceed(
|
||||
Mockito.same(request),
|
||||
Mockito.<ExecChain.Scope>any())).thenAnswer(new Answer<HttpResponse>() {
|
||||
|
||||
@Override
|
||||
public HttpResponse answer(final InvocationOnMock invocationOnMock) throws Throwable {
|
||||
Mockito.<ExecChain.Scope>any())).thenAnswer((Answer<HttpResponse>) invocationOnMock -> {
|
||||
final Object[] args = invocationOnMock.getArguments();
|
||||
final ClassicHttpRequest requestEE = (ClassicHttpRequest) args[0];
|
||||
requestEE.getEntity().writeTo(new ByteArrayOutputStream());
|
||||
return response1;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
Mockito.when(targetAuthStrategy.select(
|
||||
|
|
|
@ -438,19 +438,19 @@ public class TestRouteTracker {
|
|||
Assert.assertTrue(hs.add(rt4));
|
||||
Assert.assertTrue(hs.add(rt6));
|
||||
|
||||
Assert.assertTrue(hc0.add(Integer.valueOf(rt0.hashCode())));
|
||||
Assert.assertTrue(hc4.add(Integer.valueOf(rt4.hashCode())));
|
||||
Assert.assertTrue(hc6.add(Integer.valueOf(rt6.hashCode())));
|
||||
Assert.assertTrue(hc0.add(rt0.hashCode()));
|
||||
Assert.assertTrue(hc4.add(rt4.hashCode()));
|
||||
Assert.assertTrue(hc6.add(rt6.hashCode()));
|
||||
|
||||
rt = (RouteTracker) rt0.clone();
|
||||
rt.connectTarget(false);
|
||||
Assert.assertTrue(hs.add(rt));
|
||||
Assert.assertTrue(hc0.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc0.add(rt.hashCode()));
|
||||
|
||||
rt = (RouteTracker) rt0.clone();
|
||||
rt.connectTarget(true);
|
||||
Assert.assertTrue(hs.add(rt));
|
||||
Assert.assertTrue(hc0.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc0.add(rt.hashCode()));
|
||||
|
||||
|
||||
// proxy (insecure) -> tunnel (insecure) -> layer (secure)
|
||||
|
@ -458,15 +458,15 @@ public class TestRouteTracker {
|
|||
rt.connectProxy(PROXY1, false);
|
||||
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
|
||||
// this is not guaranteed to be unique...
|
||||
Assert.assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc4.add(rt.hashCode()));
|
||||
|
||||
rt.tunnelTarget(false);
|
||||
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
|
||||
Assert.assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc4.add(rt.hashCode()));
|
||||
|
||||
rt.layerProtocol(true);
|
||||
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
|
||||
Assert.assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc4.add(rt.hashCode()));
|
||||
|
||||
|
||||
// proxy (secure) -> tunnel (secure) -> layer (insecure)
|
||||
|
@ -474,15 +474,15 @@ public class TestRouteTracker {
|
|||
rt.connectProxy(PROXY1, true);
|
||||
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
|
||||
// this is not guaranteed to be unique...
|
||||
Assert.assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc4.add(rt.hashCode()));
|
||||
|
||||
rt.tunnelTarget(true);
|
||||
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
|
||||
Assert.assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc4.add(rt.hashCode()));
|
||||
|
||||
rt.layerProtocol(false);
|
||||
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
|
||||
Assert.assertTrue(hc4.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc4.add(rt.hashCode()));
|
||||
|
||||
|
||||
// PROXY1/i -> PROXY2/i -> tunnel/i -> layer/s
|
||||
|
@ -490,20 +490,20 @@ public class TestRouteTracker {
|
|||
rt.connectProxy(PROXY1, false);
|
||||
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
|
||||
// this is not guaranteed to be unique...
|
||||
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc6.add(rt.hashCode()));
|
||||
|
||||
rt.tunnelProxy(PROXY2, false);
|
||||
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
|
||||
// this is not guaranteed to be unique...
|
||||
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc6.add(rt.hashCode()));
|
||||
|
||||
rt.tunnelTarget(false);
|
||||
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
|
||||
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc6.add(rt.hashCode()));
|
||||
|
||||
rt.layerProtocol(true);
|
||||
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
|
||||
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc6.add(rt.hashCode()));
|
||||
|
||||
|
||||
// PROXY1/s -> PROXY2/s -> tunnel/s -> layer/i
|
||||
|
@ -511,20 +511,20 @@ public class TestRouteTracker {
|
|||
rt.connectProxy(PROXY1, true);
|
||||
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
|
||||
// this is not guaranteed to be unique...
|
||||
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc6.add(rt.hashCode()));
|
||||
|
||||
rt.tunnelProxy(PROXY2, true);
|
||||
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
|
||||
// this is not guaranteed to be unique...
|
||||
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc6.add(rt.hashCode()));
|
||||
|
||||
rt.tunnelTarget(true);
|
||||
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
|
||||
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc6.add(rt.hashCode()));
|
||||
|
||||
rt.layerProtocol(false);
|
||||
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
|
||||
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc6.add(rt.hashCode()));
|
||||
|
||||
|
||||
// PROXY2/i -> PROXY1/i -> tunnel/i -> layer/s
|
||||
|
@ -532,7 +532,7 @@ public class TestRouteTracker {
|
|||
rt.connectProxy(PROXY2, false);
|
||||
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
|
||||
// this is not guaranteed to be unique...
|
||||
Assert.assertTrue(hc6.add(Integer.valueOf(rt.hashCode())));
|
||||
Assert.assertTrue(hc6.add(rt.hashCode()));
|
||||
|
||||
rt.tunnelProxy(PROXY1, false);
|
||||
Assert.assertTrue(hs.add((RouteTracker) rt.clone()));
|
||||
|
|
|
@ -29,7 +29,6 @@ package org.apache.hc.client5.http.routing;
|
|||
|
||||
import java.net.InetAddress;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.hc.client5.http.HttpRoute;
|
||||
|
@ -201,14 +200,14 @@ public class TestHttpRoute {
|
|||
// we can't test hashCode in general due to its dependency
|
||||
// on InetAddress and HttpHost, but we can check for the flags
|
||||
final Set<Integer> routecodes = new HashSet<>();
|
||||
routecodes.add(Integer.valueOf(routefff.hashCode()));
|
||||
routecodes.add(Integer.valueOf(routefft.hashCode()));
|
||||
routecodes.add(Integer.valueOf(routeftf.hashCode()));
|
||||
routecodes.add(Integer.valueOf(routeftt.hashCode()));
|
||||
routecodes.add(Integer.valueOf(routetff.hashCode()));
|
||||
routecodes.add(Integer.valueOf(routetft.hashCode()));
|
||||
routecodes.add(Integer.valueOf(routettf.hashCode()));
|
||||
routecodes.add(Integer.valueOf(routettt.hashCode()));
|
||||
routecodes.add(routefff.hashCode());
|
||||
routecodes.add(routefft.hashCode());
|
||||
routecodes.add(routeftf.hashCode());
|
||||
routecodes.add(routeftt.hashCode());
|
||||
routecodes.add(routetff.hashCode());
|
||||
routecodes.add(routetft.hashCode());
|
||||
routecodes.add(routettf.hashCode());
|
||||
routecodes.add(routettt.hashCode());
|
||||
Assert.assertEquals("some flagged routes have same hashCode",
|
||||
8, routecodes.size());
|
||||
|
||||
|
@ -394,9 +393,7 @@ public class TestHttpRoute {
|
|||
Assert.assertEquals("some routes are equal", 11, routes.size());
|
||||
|
||||
// and a run of cloning over the set
|
||||
final Iterator<HttpRoute> iter = routes.iterator();
|
||||
while (iter.hasNext()) {
|
||||
final HttpRoute origin = iter.next();
|
||||
for (final HttpRoute origin : routes) {
|
||||
final HttpRoute cloned = (HttpRoute) origin.clone();
|
||||
Assert.assertEquals("clone of " + origin, origin, cloned);
|
||||
Assert.assertTrue("clone of " + origin, routes.contains(cloned));
|
||||
|
|
4
pom.xml
4
pom.xml
|
@ -60,8 +60,8 @@
|
|||
</distributionManagement>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.7</maven.compiler.source>
|
||||
<maven.compiler.target>1.7</maven.compiler.target>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<httpcore.version>5.1.1</httpcore.version>
|
||||
<log4j.version>2.9.1</log4j.version>
|
||||
<commons-codec.version>1.15</commons-codec.version>
|
||||
|
|
Loading…
Reference in New Issue