Upgraded HC StyleCheck to version 3; fixed style-check violations (no functional changes)

This commit is contained in:
Oleg Kalnichevski 2024-09-26 16:32:16 +02:00
parent db623f8854
commit 9941fde19e
125 changed files with 616 additions and 609 deletions

View File

@ -165,7 +165,8 @@ public class HeaderConstants {
public static final String CACHE_CONTROL_STALE_WHILE_REVALIDATE = "stale-while-revalidate"; public static final String CACHE_CONTROL_STALE_WHILE_REVALIDATE = "stale-while-revalidate";
public static final String CACHE_CONTROL_ONLY_IF_CACHED = "only-if-cached"; public static final String CACHE_CONTROL_ONLY_IF_CACHED = "only-if-cached";
public static final String CACHE_CONTROL_MUST_UNDERSTAND = "must-understand"; public static final String CACHE_CONTROL_MUST_UNDERSTAND = "must-understand";
public static final String CACHE_CONTROL_IMMUTABLE= "immutable"; public static final String CACHE_CONTROL_IMMUTABLE = "immutable";
/** /**
* @deprecated Use {@link #CACHE_CONTROL_STALE_IF_ERROR} * @deprecated Use {@link #CACHE_CONTROL_STALE_IF_ERROR}
*/ */

View File

@ -227,7 +227,7 @@ public class CacheConfig implements Cloneable {
/** /**
* Returns the number of times to retry a cache processChallenge on failure * Returns the number of times to retry a cache processChallenge on failure
*/ */
public int getMaxUpdateRetries(){ public int getMaxUpdateRetries() {
return maxUpdateRetries; return maxUpdateRetries;
} }

View File

@ -198,7 +198,7 @@ class CachedResponseSuitabilityChecker {
boolean requestMethodMatch(final HttpRequest request, final HttpCacheEntry entry) { boolean requestMethodMatch(final HttpRequest request, final HttpCacheEntry entry) {
return request.getMethod().equalsIgnoreCase(entry.getRequestMethod()) || return request.getMethod().equalsIgnoreCase(entry.getRequestMethod()) ||
(Method.HEAD.isSame(request.getMethod()) && Method.GET.isSame(entry.getRequestMethod())); Method.HEAD.isSame(request.getMethod()) && Method.GET.isSame(entry.getRequestMethod());
} }
boolean requestUriMatch(final HttpRequest request, final HttpCacheEntry entry) { boolean requestUriMatch(final HttpRequest request, final HttpCacheEntry entry) {
@ -295,10 +295,10 @@ class CachedResponseSuitabilityChecker {
return true; return true;
} }
final boolean etagValidatorMatches = (hasEtagValidator) && etagValidatorMatches(request, entry); final boolean etagValidatorMatches = hasEtagValidator && etagValidatorMatches(request, entry);
final boolean lastModifiedValidatorMatches = (hasLastModifiedValidator) && lastModifiedValidatorMatches(request, entry, now); final boolean lastModifiedValidatorMatches = hasLastModifiedValidator && lastModifiedValidatorMatches(request, entry, now);
if ((hasEtagValidator && hasLastModifiedValidator) if (hasEtagValidator && hasLastModifiedValidator
&& !(etagValidatorMatches && lastModifiedValidatorMatches)) { && !(etagValidatorMatches && lastModifiedValidatorMatches)) {
return false; return false;
} else if (hasEtagValidator && !etagValidatorMatches) { } else if (hasEtagValidator && !etagValidatorMatches) {
@ -309,9 +309,9 @@ class CachedResponseSuitabilityChecker {
} }
boolean hasUnsupportedConditionalHeaders(final HttpRequest request) { boolean hasUnsupportedConditionalHeaders(final HttpRequest request) {
return (request.containsHeader(HttpHeaders.IF_RANGE) return request.containsHeader(HttpHeaders.IF_RANGE)
|| request.containsHeader(HttpHeaders.IF_MATCH) || request.containsHeader(HttpHeaders.IF_MATCH)
|| request.containsHeader(HttpHeaders.IF_UNMODIFIED_SINCE)); || request.containsHeader(HttpHeaders.IF_UNMODIFIED_SINCE);
} }
boolean hasSupportedEtagValidator(final HttpRequest request) { boolean hasSupportedEtagValidator(final HttpRequest request) {

View File

@ -240,7 +240,8 @@ public class ManagedHttpCacheStorage implements HttpCacheStorage, Closeable {
return active.get(); return active.get();
} }
private boolean compareAndSet(){ private boolean compareAndSet() {
return this.active.compareAndSet(true, false); return this.active.compareAndSet(true, false);
} }
} }

View File

@ -235,7 +235,7 @@ class ResponseCachingPolicy {
// The response is considered explicitly non-cacheable if it contains // The response is considered explicitly non-cacheable if it contains
// "no-store" or (if sharedCache is true) "private" directives. // "no-store" or (if sharedCache is true) "private" directives.
// Note that "no-cache" is considered cacheable but requires validation before use. // Note that "no-cache" is considered cacheable but requires validation before use.
return cacheControl.isNoStore() || (sharedCache && cacheControl.isCachePrivate()); return cacheControl.isNoStore() || sharedCache && cacheControl.isCachePrivate();
} }
protected boolean isExplicitlyCacheable(final ResponseCacheControl cacheControl, final HttpResponse response) { protected boolean isExplicitlyCacheable(final ResponseCacheControl cacheControl, final HttpResponse response) {
@ -371,11 +371,11 @@ class ResponseCachingPolicy {
* @return true if the HTTP status code is understood, false otherwise. * @return true if the HTTP status code is understood, false otherwise.
*/ */
private boolean understoodStatusCode(final int status) { private boolean understoodStatusCode(final int status) {
return (status >= 200 && status <= 206) || return status >= 200 && status <= 206 ||
(status >= 300 && status <= 399) || status >= 300 && status <= 399 ||
(status >= 400 && status <= 417) || status >= 400 && status <= 417 ||
(status == 421) || status == 421 ||
(status >= 500 && status <= 505); status >= 500 && status <= 505;
} }
/** /**

View File

@ -176,7 +176,7 @@ class TestHttpCacheEntry {
entry = makeEntry(Instant.now(), Instant.now(), HttpStatus.SC_OK, headers, mockResource, null); entry = makeEntry(Instant.now(), Instant.now(), HttpStatus.SC_OK, headers, mockResource, null);
final Header[] result = entry.getHeaders(); final Header[] result = entry.getHeaders();
assertEquals(headers.length, result.length); assertEquals(headers.length, result.length);
for(int i=0; i<headers.length; i++) { for (int i = 0; i < headers.length; i++) {
assertEquals(headers[i], result[i]); assertEquals(headers[i], result[i]);
} }
} }

View File

@ -80,7 +80,7 @@ public class HttpTestUtils {
return false; return false;
} }
} }
return (-1 == i2.read()); return -1 == i2.read();
} }
/* /*

View File

@ -73,7 +73,7 @@ class TestAbstractSerializingAsyncCacheStorage {
@BeforeEach @BeforeEach
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void setUp() { void setUp() {
MockitoAnnotations.openMocks(this); MockitoAnnotations.openMocks(this);
impl = Mockito.mock(AbstractBinaryAsyncCacheStorage.class, impl = Mockito.mock(AbstractBinaryAsyncCacheStorage.class,
Mockito.withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS).useConstructor(3)); Mockito.withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS).useConstructor(3));

View File

@ -61,7 +61,7 @@ class TestAbstractSerializingCacheStorage {
@BeforeEach @BeforeEach
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void setUp() { void setUp() {
impl = Mockito.mock(AbstractBinaryCacheStorage.class, impl = Mockito.mock(AbstractBinaryCacheStorage.class,
Mockito.withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS).useConstructor(3)); Mockito.withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS).useConstructor(3));
} }
@ -125,7 +125,7 @@ class TestAbstractSerializingCacheStorage {
} }
@Test @Test
void testCacheRemove() throws Exception{ void testCacheRemove() throws Exception {
final String key = "foo"; final String key = "foo";
when(impl.digestToStorageKey(key)).thenReturn("bar"); when(impl.digestToStorageKey(key)).thenReturn("bar");

View File

@ -399,7 +399,7 @@ class TestHttpByteArrayCacheEntrySerializer {
*/ */
@Test @Test
void testDeserializeCacheEntryWithTrailingGarbage() { void testDeserializeCacheEntryWithTrailingGarbage() {
final String content1 =HttpByteArrayCacheEntrySerializer.HC_CACHE_VERSION_LINE + "\n" + final String content1 = HttpByteArrayCacheEntrySerializer.HC_CACHE_VERSION_LINE + "\n" +
"HC-Key: unique-cache-key\n" + "HC-Key: unique-cache-key\n" +
"HC-Resource-Length: 11\n" + "HC-Resource-Length: 11\n" +
"HC-Request-Instant: 1686210849596\n" + "HC-Request-Instant: 1686210849596\n" +
@ -417,7 +417,7 @@ class TestHttpByteArrayCacheEntrySerializer {
httpCacheEntrySerializer.deserialize(bytes1)); httpCacheEntrySerializer.deserialize(bytes1));
Assertions.assertEquals("Unexpected content at the end of cache content", exception1.getMessage()); Assertions.assertEquals("Unexpected content at the end of cache content", exception1.getMessage());
final String content2 =HttpByteArrayCacheEntrySerializer.HC_CACHE_VERSION_LINE + "\n" + final String content2 = HttpByteArrayCacheEntrySerializer.HC_CACHE_VERSION_LINE + "\n" +
"HC-Key: unique-cache-key\n" + "HC-Key: unique-cache-key\n" +
"HC-Request-Instant: 1686210849596\n" + "HC-Request-Instant: 1686210849596\n" +
"HC-Response-Instant: 1686210849596\n" + "HC-Response-Instant: 1686210849596\n" +

View File

@ -268,7 +268,7 @@ class TestProtocolRecommendations {
ClassicHttpResponse result = null; ClassicHttpResponse result = null;
try { try {
result = execute(req2); result = execute(req2);
} catch (final IOException acceptable) { } catch (final IOException expected) {
} }
if (result != null) { if (result != null) {
@ -745,8 +745,8 @@ class TestProtocolRecommendations {
final ClassicHttpRequest captured = reqCapture.getValue(); final ClassicHttpRequest captured = reqCapture.getValue();
boolean foundEtag1 = false; boolean foundEtag1 = false;
boolean foundEtag2 = false; boolean foundEtag2 = false;
for(final Header h : captured.getHeaders("If-None-Match")) { for (final Header h : captured.getHeaders("If-None-Match")) {
for(final String etag : h.getValue().split(",")) { for (final String etag : h.getValue().split(",")) {
if ("\"etag1\"".equals(etag.trim())) { if ("\"etag1\"".equals(etag.trim())) {
foundEtag1 = true; foundEtag1 = true;
} }

View File

@ -1212,7 +1212,7 @@ class TestProtocolRequirements {
try (final InputStream i1 = resp1.getEntity().getContent(); try (final InputStream i1 = resp1.getEntity().getContent();
final InputStream i2 = result.getEntity().getContent()) { final InputStream i2 = result.getEntity().getContent()) {
int b1, b2; int b1, b2;
while((b1 = i1.read()) != -1) { while ((b1 = i1.read()) != -1) {
b2 = i2.read(); b2 = i2.read();
Assertions.assertEquals(b1, b2); Assertions.assertEquals(b1, b2);
} }
@ -1262,7 +1262,7 @@ class TestProtocolRequirements {
"Content-MD5", "Content-Type", "Expires", "Last-Modified", "Content-MD5", "Content-Type", "Expires", "Last-Modified",
"Location", "Retry-After" "Location", "Retry-After"
}; };
for(final String h : endToEndHeaders) { for (final String h : endToEndHeaders) {
Assertions.assertEquals(HttpTestUtils.getCanonicalHeaderValue(resp1, h), Assertions.assertEquals(HttpTestUtils.getCanonicalHeaderValue(resp1, h),
HttpTestUtils.getCanonicalHeaderValue(result, h)); HttpTestUtils.getCanonicalHeaderValue(result, h));
} }
@ -1306,7 +1306,7 @@ class TestProtocolRequirements {
"Content-Location", "Content-Type", "Expires", "Location", "Content-Location", "Content-Type", "Expires", "Location",
"Retry-After" "Retry-After"
}; };
for(final String h : endToEndHeaders) { for (final String h : endToEndHeaders) {
Assertions.assertEquals(HttpTestUtils.getCanonicalHeaderValue(resp2, h), Assertions.assertEquals(HttpTestUtils.getCanonicalHeaderValue(resp2, h),
HttpTestUtils.getCanonicalHeaderValue(result1, h)); HttpTestUtils.getCanonicalHeaderValue(result1, h));
Assertions.assertEquals(HttpTestUtils.getCanonicalHeaderValue(resp2, h), Assertions.assertEquals(HttpTestUtils.getCanonicalHeaderValue(resp2, h),
@ -2093,7 +2093,7 @@ class TestProtocolRequirements {
final Iterator<HeaderElement> it = MessageSupport.iterate(result, HttpHeaders.CONTENT_ENCODING); final Iterator<HeaderElement> it = MessageSupport.iterate(result, HttpHeaders.CONTENT_ENCODING);
while (it.hasNext()) { while (it.hasNext()) {
final HeaderElement elt = it.next(); final HeaderElement elt = it.next();
switch(total_encodings) { switch (total_encodings) {
case 0: case 0:
Assertions.assertEquals("gzip", elt.getName()); Assertions.assertEquals("gzip", elt.getName());
break; break;
@ -2118,7 +2118,7 @@ class TestProtocolRequirements {
final Iterator<HeaderElement> it = MessageSupport.iterate(result, HttpHeaders.CONTENT_ENCODING); final Iterator<HeaderElement> it = MessageSupport.iterate(result, HttpHeaders.CONTENT_ENCODING);
while (it.hasNext()) { while (it.hasNext()) {
final HeaderElement elt = it.next(); final HeaderElement elt = it.next();
switch(total_encodings) { switch (total_encodings) {
case 0: case 0:
Assertions.assertEquals("gzip", elt.getName()); Assertions.assertEquals("gzip", elt.getName());
break; break;

View File

@ -126,8 +126,7 @@ class TestRFC5861Compliance {
} }
@Test @Test
void testConsumesErrorResponseWhenServingStale() void testConsumesErrorResponseWhenServingStale() throws Exception {
throws Exception{
final Instant tenSecondsAgo = Instant.now().minusSeconds(10); final Instant tenSecondsAgo = Instant.now().minusSeconds(10);
final ClassicHttpRequest req1 = HttpTestUtils.makeDefaultRequest(); final ClassicHttpRequest req1 = HttpTestUtils.makeDefaultRequest();
final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo,
@ -152,8 +151,7 @@ class TestRFC5861Compliance {
} }
@Test @Test
void testStaleIfErrorInResponseYieldsToMustRevalidate() void testStaleIfErrorInResponseYieldsToMustRevalidate() throws Exception {
throws Exception{
final Instant tenSecondsAgo = Instant.now().minusSeconds(10); final Instant tenSecondsAgo = Instant.now().minusSeconds(10);
final ClassicHttpRequest req1 = HttpTestUtils.makeDefaultRequest(); final ClassicHttpRequest req1 = HttpTestUtils.makeDefaultRequest();
final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo,
@ -174,8 +172,7 @@ class TestRFC5861Compliance {
} }
@Test @Test
void testStaleIfErrorInResponseYieldsToProxyRevalidateForSharedCache() void testStaleIfErrorInResponseYieldsToProxyRevalidateForSharedCache() throws Exception {
throws Exception{
assertTrue(config.isSharedCache()); assertTrue(config.isSharedCache());
final Instant tenSecondsAgo = Instant.now().minusSeconds(10); final Instant tenSecondsAgo = Instant.now().minusSeconds(10);
final ClassicHttpRequest req1 = HttpTestUtils.makeDefaultRequest(); final ClassicHttpRequest req1 = HttpTestUtils.makeDefaultRequest();
@ -197,8 +194,7 @@ class TestRFC5861Compliance {
} }
@Test @Test
void testStaleIfErrorInResponseYieldsToExplicitFreshnessRequest() void testStaleIfErrorInResponseYieldsToExplicitFreshnessRequest() throws Exception {
throws Exception{
final Instant tenSecondsAgo = Instant.now().minusSeconds(10); final Instant tenSecondsAgo = Instant.now().minusSeconds(10);
final ClassicHttpRequest req1 = HttpTestUtils.makeDefaultRequest(); final ClassicHttpRequest req1 = HttpTestUtils.makeDefaultRequest();
final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo, final ClassicHttpResponse resp1 = HttpTestUtils.make200Response(tenSecondsAgo,
@ -220,8 +216,7 @@ class TestRFC5861Compliance {
} }
@Test @Test
void testStaleIfErrorInResponseIsFalseReturnsError() void testStaleIfErrorInResponseIsFalseReturnsError() throws Exception {
throws Exception{
final Instant now = Instant.now(); final Instant now = Instant.now();
final Instant tenSecondsAgo = now.minusSeconds(10); final Instant tenSecondsAgo = now.minusSeconds(10);
final ClassicHttpRequest req1 = HttpTestUtils.makeDefaultRequest(); final ClassicHttpRequest req1 = HttpTestUtils.makeDefaultRequest();
@ -244,8 +239,7 @@ class TestRFC5861Compliance {
} }
@Test @Test
void testStaleIfErrorInRequestIsFalseReturnsError() void testStaleIfErrorInRequestIsFalseReturnsError() throws Exception {
throws Exception{
final Instant now = Instant.now(); final Instant now = Instant.now();
final Instant tenSecondsAgo = now.minusSeconds(10); final Instant tenSecondsAgo = now.minusSeconds(10);
final ClassicHttpRequest req1 = HttpTestUtils.makeDefaultRequest(); final ClassicHttpRequest req1 = HttpTestUtils.makeDefaultRequest();

View File

@ -364,7 +364,7 @@ public class Request {
return this; return this;
} }
public Request bodyForm(final Iterable <? extends NameValuePair> formParams, final Charset charset) { public Request bodyForm(final Iterable<? extends NameValuePair> formParams, final Charset charset) {
final List<NameValuePair> paramList = new ArrayList<>(); final List<NameValuePair> paramList = new ArrayList<>();
for (final NameValuePair param : formParams) { for (final NameValuePair param : formParams) {
paramList.add(param); paramList.add(param);
@ -375,7 +375,7 @@ public class Request {
return bodyString(s, contentType); return bodyString(s, contentType);
} }
public Request bodyForm(final Iterable <? extends NameValuePair> formParams) { public Request bodyForm(final Iterable<? extends NameValuePair> formParams) {
return bodyForm(formParams, StandardCharsets.ISO_8859_1); return bodyForm(formParams, StandardCharsets.ISO_8859_1);
} }

View File

@ -80,11 +80,11 @@ public class FluentAsync {
queue.add(future); queue.add(future);
} }
while(!queue.isEmpty()) { while (!queue.isEmpty()) {
final Future<Content> future = queue.remove(); final Future<Content> future = queue.remove();
try { try {
future.get(); future.get();
} catch (final ExecutionException ex) { } catch (final ExecutionException ignore) {
} }
} }
System.out.println("Done"); System.out.println("Done");

View File

@ -195,7 +195,7 @@ public class RandomHandler implements HttpRequestHandler {
double value = 0.0; double value = 0.0;
for (int i = 0; i < end; i++) { for (int i = 0; i < end; i++) {
// we get 5 random characters out of one random value // we get 5 random characters out of one random value
if (i%5 == 0) { if (i % 5 == 0) {
value = Math.random(); value = Math.random();
} }
value = value * RANGE.length; value = value * RANGE.length;

View File

@ -85,7 +85,7 @@ abstract class AbstractHttpReactiveFundamentalsTest extends AbstractIntegration
@Test @Test
@Timeout(value = 60_000, unit = MILLISECONDS) @Timeout(value = 60_000, unit = MILLISECONDS)
public void testSequentialGetRequests() throws Exception { void testSequentialGetRequests() throws Exception {
configureServer(bootstrap -> bootstrap configureServer(bootstrap -> bootstrap
.register("/random/*", () -> new ReactiveServerExchangeHandler(new ReactiveRandomProcessor()))); .register("/random/*", () -> new ReactiveServerExchangeHandler(new ReactiveRandomProcessor())));
final HttpHost target = startServer(); final HttpHost target = startServer();
@ -108,7 +108,7 @@ abstract class AbstractHttpReactiveFundamentalsTest extends AbstractIntegration
@Test @Test
@Timeout(value = 2000, unit = MILLISECONDS) @Timeout(value = 2000, unit = MILLISECONDS)
public void testSequentialHeadRequests() throws Exception { void testSequentialHeadRequests() throws Exception {
configureServer(bootstrap -> bootstrap.register("/random/*", () -> configureServer(bootstrap -> bootstrap.register("/random/*", () ->
new ReactiveServerExchangeHandler(new ReactiveRandomProcessor()))); new ReactiveServerExchangeHandler(new ReactiveRandomProcessor())));
final HttpHost target = startServer(); final HttpHost target = startServer();
@ -130,7 +130,7 @@ abstract class AbstractHttpReactiveFundamentalsTest extends AbstractIntegration
@Test @Test
@Timeout(value = 60_000, unit = MILLISECONDS) @Timeout(value = 60_000, unit = MILLISECONDS)
public void testSequentialPostRequests() throws Exception { void testSequentialPostRequests() throws Exception {
configureServer(bootstrap -> bootstrap.register("/echo/*", () -> configureServer(bootstrap -> bootstrap.register("/echo/*", () ->
new ReactiveServerExchangeHandler(new ReactiveEchoProcessor()))); new ReactiveServerExchangeHandler(new ReactiveEchoProcessor())));
final HttpHost target = startServer(); final HttpHost target = startServer();
@ -160,7 +160,7 @@ abstract class AbstractHttpReactiveFundamentalsTest extends AbstractIntegration
@Test @Test
@Timeout(value = 60_000, unit = MILLISECONDS) @Timeout(value = 60_000, unit = MILLISECONDS)
public void testConcurrentPostRequests() throws Exception { void testConcurrentPostRequests() throws Exception {
configureServer(bootstrap -> bootstrap.register("/echo/*", () -> configureServer(bootstrap -> bootstrap.register("/echo/*", () ->
new ReactiveServerExchangeHandler(new ReactiveEchoProcessor()))); new ReactiveServerExchangeHandler(new ReactiveEchoProcessor())));
final HttpHost target = startServer(); final HttpHost target = startServer();
@ -209,7 +209,7 @@ abstract class AbstractHttpReactiveFundamentalsTest extends AbstractIntegration
@Test @Test
@Timeout(value = 60_000, unit = MILLISECONDS) @Timeout(value = 60_000, unit = MILLISECONDS)
public void testRequestExecutionFromCallback() throws Exception { void testRequestExecutionFromCallback() throws Exception {
configureServer(bootstrap -> bootstrap.register("/random/*", () -> configureServer(bootstrap -> bootstrap.register("/random/*", () ->
new ReactiveServerExchangeHandler(new ReactiveRandomProcessor()))); new ReactiveServerExchangeHandler(new ReactiveRandomProcessor())));
final HttpHost target = startServer(); final HttpHost target = startServer();

View File

@ -99,7 +99,7 @@ abstract class TestHttp1Reactive extends AbstractHttpReactiveFundamentalsTest {
@Test @Test
@Timeout(value = 60_000, unit = MILLISECONDS) @Timeout(value = 60_000, unit = MILLISECONDS)
public void testSharedPool() throws Exception { void testSharedPool() throws Exception {
configureServer(bootstrap -> bootstrap.register("/random/*", () -> configureServer(bootstrap -> bootstrap.register("/random/*", () ->
new ReactiveServerExchangeHandler(new ReactiveRandomProcessor()))); new ReactiveServerExchangeHandler(new ReactiveRandomProcessor())));
final HttpHost target = startServer(); final HttpHost target = startServer();

View File

@ -107,7 +107,7 @@ public class CachingHttpAsyncClientCompatibilityTest {
client.close(); client.close();
} }
enum TestResult {OK, NOK} enum TestResult { OK, NOK }
private void logResult(final TestResult result, private void logResult(final TestResult result,
final HttpRequest request, final HttpRequest request,
@ -186,7 +186,7 @@ public class CachingHttpAsyncClientCompatibilityTest {
final Throwable cause = ex.getCause(); final Throwable cause = ex.getCause();
logResult(TestResult.NOK, httpGet1, null, "(" + cause.getMessage() + ")"); logResult(TestResult.NOK, httpGet1, null, "(" + cause.getMessage() + ")");
} catch (final TimeoutException ex) { } catch (final TimeoutException ex) {
logResult(TestResult.NOK, httpGet1, null,"(time out)"); logResult(TestResult.NOK, httpGet1, null, "(time out)");
} }
final SimpleHttpRequest httpGet2 = SimpleRequestBuilder.get() final SimpleHttpRequest httpGet2 = SimpleRequestBuilder.get()
@ -207,7 +207,7 @@ public class CachingHttpAsyncClientCompatibilityTest {
final Throwable cause = ex.getCause(); final Throwable cause = ex.getCause();
logResult(TestResult.NOK, httpGet2, null, "(" + cause.getMessage() + ")"); logResult(TestResult.NOK, httpGet2, null, "(" + cause.getMessage() + ")");
} catch (final TimeoutException ex) { } catch (final TimeoutException ex) {
logResult(TestResult.NOK, httpGet2, null,"(time out)"); logResult(TestResult.NOK, httpGet2, null, "(time out)");
} }
Thread.sleep(2000); Thread.sleep(2000);
@ -231,7 +231,7 @@ public class CachingHttpAsyncClientCompatibilityTest {
final Throwable cause = ex.getCause(); final Throwable cause = ex.getCause();
logResult(TestResult.NOK, httpGet3, null, "(" + cause.getMessage() + ")"); logResult(TestResult.NOK, httpGet3, null, "(" + cause.getMessage() + ")");
} catch (final TimeoutException ex) { } catch (final TimeoutException ex) {
logResult(TestResult.NOK, httpGet3, null,"(time out)"); logResult(TestResult.NOK, httpGet3, null, "(time out)");
} }
} }
} }

View File

@ -92,7 +92,7 @@ public class CachingHttpClientCompatibilityTest {
client.close(); client.close();
} }
enum TestResult {OK, NOK} enum TestResult { OK, NOK }
private void logResult(final TestResult result, final HttpRequest request, final String message) { private void logResult(final TestResult result, final HttpRequest request, final String message) {
final StringBuilder buf = new StringBuilder(); final StringBuilder buf = new StringBuilder();

View File

@ -155,7 +155,7 @@ public class HttpAsyncClientCompatibilityTest {
client.close(); client.close();
} }
enum TestResult {OK, NOK} enum TestResult { OK, NOK }
private void logResult(final TestResult result, private void logResult(final TestResult result,
final HttpRequest request, final HttpRequest request,

View File

@ -115,7 +115,7 @@ public class HttpClientCompatibilityTest {
client.close(); client.close();
} }
enum TestResult {OK, NOK} enum TestResult { OK, NOK }
private void logResult(final TestResult result, final HttpRequest request, final String message) { private void logResult(final TestResult result, final HttpRequest request, final String message) {
final StringBuilder buf = new StringBuilder(); final StringBuilder buf = new StringBuilder();

View File

@ -313,7 +313,7 @@ abstract class TestClientRequestExecution extends AbstractIntegrationTestBase {
} }
@Test @Disabled("Fails intermittently with GitHub Actions") @Test @Disabled("Fails intermittently with GitHub Actions")
public void testRequestCancellation() throws Exception { void testRequestCancellation() throws Exception {
startServer(); startServer();
final HttpHost target = startServer(); final HttpHost target = startServer();

View File

@ -350,8 +350,8 @@ class TestConnectionReuse extends AbstractIntegrationTestBase {
final EntityDetails entityDetails, final EntityDetails entityDetails,
final HttpContext context) { final HttpContext context) {
final Header connection = response.getFirstHeader(HttpHeaders.CONNECTION); final Header connection = response.getFirstHeader(HttpHeaders.CONNECTION);
if(connection != null) { if (connection != null) {
if(!connection.getValue().equalsIgnoreCase("Close")) { if (!connection.getValue().equalsIgnoreCase("Close")) {
response.addHeader(HeaderElements.KEEP_ALIVE, "timeout=1"); response.addHeader(HeaderElements.KEEP_ALIVE, "timeout=1");
} }
} }

View File

@ -74,7 +74,7 @@ class TestFutureRequestExecutionService {
.setCanonicalHostName("localhost") .setCanonicalHostName("localhost")
.register("/wait", (request, response, context) -> { .register("/wait", (request, response, context) -> {
try { try {
while(blocked.get()) { while (blocked.get()) {
Thread.sleep(10); Thread.sleep(10);
} }
} catch (final InterruptedException e) { } catch (final InterruptedException e) {
@ -133,7 +133,7 @@ class TestFutureRequestExecutionService {
void shouldExecuteMultipleCalls() throws Exception { void shouldExecuteMultipleCalls() throws Exception {
final int reqNo = 100; final int reqNo = 100;
final Queue<Future<Boolean>> tasks = new LinkedList<>(); final Queue<Future<Boolean>> tasks = new LinkedList<>();
for(int i = 0; i < reqNo; i++) { for (int i = 0; i < reqNo; i++) {
final Future<Boolean> task = httpAsyncClientWithFuture.execute( final Future<Boolean> task = httpAsyncClientWithFuture.execute(
new HttpGet(uri), HttpClientContext.create(), new OkidokiHandler()); new HttpGet(uri), HttpClientContext.create(), new OkidokiHandler());
tasks.add(task); tasks.add(task);
@ -150,7 +150,7 @@ class TestFutureRequestExecutionService {
final int reqNo = 100; final int reqNo = 100;
final Queue<Future<Boolean>> tasks = new LinkedList<>(); final Queue<Future<Boolean>> tasks = new LinkedList<>();
final CountDownLatch latch = new CountDownLatch(reqNo); final CountDownLatch latch = new CountDownLatch(reqNo);
for(int i = 0; i < reqNo; i++) { for (int i = 0; i < reqNo; i++) {
final Future<Boolean> task = httpAsyncClientWithFuture.execute( final Future<Boolean> task = httpAsyncClientWithFuture.execute(
new HttpGet(uri), HttpClientContext.create(), new HttpGet(uri), HttpClientContext.create(),
new OkidokiHandler(), new CountingCallback(latch)); new OkidokiHandler(), new CountingCallback(latch));

View File

@ -307,7 +307,7 @@ public final class HttpRoute implements RouteInfo, Cloneable {
@Override @Override
public boolean isTunnelled() { public boolean isTunnelled() {
return (this.tunnelled == TunnelType.TUNNELLED); return this.tunnelled == TunnelType.TUNNELLED;
} }
@Override @Override
@ -317,7 +317,7 @@ public final class HttpRoute implements RouteInfo, Cloneable {
@Override @Override
public boolean isLayered() { public boolean isLayered() {
return (this.layered == LayerType.LAYERED); return this.layered == LayerType.LAYERED;
} }
@Override @Override
@ -342,9 +342,9 @@ public final class HttpRoute implements RouteInfo, Cloneable {
final HttpRoute that = (HttpRoute) obj; final HttpRoute that = (HttpRoute) obj;
return return
// Do the cheapest tests first // Do the cheapest tests first
(this.secure == that.secure) && this.secure == that.secure &&
(this.tunnelled == that.tunnelled) && this.tunnelled == that.tunnelled &&
(this.layered == that.layered) && this.layered == that.layered &&
Objects.equals(this.targetHost, that.targetHost) && Objects.equals(this.targetHost, that.targetHost) &&
Objects.equals(this.targetName, that.targetName) && Objects.equals(this.targetName, that.targetName) &&
Objects.equals(this.localAddress, that.localAddress) && Objects.equals(this.localAddress, that.localAddress) &&
@ -383,7 +383,7 @@ public final class HttpRoute implements RouteInfo, Cloneable {
*/ */
@Override @Override
public String toString() { public String toString() {
final StringBuilder cab = new StringBuilder(50 + getHopCount()*30); final StringBuilder cab = new StringBuilder(50 + getHopCount() * 30);
if (this.localAddress != null) { if (this.localAddress != null) {
cab.append(this.localAddress); cab.append(this.localAddress);
cab.append("->"); cab.append("->");

View File

@ -130,7 +130,7 @@ public final class RouteTracker implements RouteInfo, Cloneable {
Args.notNull(proxy, "Proxy host"); Args.notNull(proxy, "Proxy host");
Asserts.check(!this.connected, "Already connected"); Asserts.check(!this.connected, "Already connected");
this.connected = true; this.connected = true;
this.proxyChain = new HttpHost[]{ proxy }; this.proxyChain = new HttpHost[]{proxy};
this.secure = secure; this.secure = secure;
} }
@ -161,10 +161,10 @@ public final class RouteTracker implements RouteInfo, Cloneable {
Asserts.check(this.connected, "No tunnel unless connected"); Asserts.check(this.connected, "No tunnel unless connected");
Asserts.notNull(this.proxyChain, "No tunnel without proxy"); Asserts.notNull(this.proxyChain, "No tunnel without proxy");
// prepare an extended proxy chain // prepare an extended proxy chain
final HttpHost[] proxies = new HttpHost[this.proxyChain.length+1]; final HttpHost[] proxies = new HttpHost[this.proxyChain.length + 1];
System.arraycopy(this.proxyChain, 0, System.arraycopy(this.proxyChain, 0,
proxies, 0, this.proxyChain.length); proxies, 0, this.proxyChain.length);
proxies[proxies.length-1] = proxy; proxies[proxies.length - 1] = proxy;
this.proxyChain = proxies; this.proxyChain = proxies;
this.secure = secure; this.secure = secure;
@ -213,7 +213,7 @@ public final class RouteTracker implements RouteInfo, Cloneable {
final int hopcount = getHopCount(); final int hopcount = getHopCount();
Args.check(hop < hopcount, "Hop index exceeds tracked route length"); Args.check(hop < hopcount, "Hop index exceeds tracked route length");
HttpHost result = null; HttpHost result = null;
if (hop < hopcount-1) { if (hop < hopcount - 1) {
result = this.proxyChain[hop]; result = this.proxyChain[hop];
} else { } else {
result = this.targetHost; result = this.targetHost;
@ -224,7 +224,7 @@ public final class RouteTracker implements RouteInfo, Cloneable {
@Override @Override
public HttpHost getProxyHost() { public HttpHost getProxyHost() {
return (this.proxyChain == null) ? null : this.proxyChain[0]; return this.proxyChain == null ? null : this.proxyChain[0];
} }
public boolean isConnected() { public boolean isConnected() {
@ -238,7 +238,7 @@ public final class RouteTracker implements RouteInfo, Cloneable {
@Override @Override
public boolean isTunnelled() { public boolean isTunnelled() {
return (this.tunnelled == TunnelType.TUNNELLED); return this.tunnelled == TunnelType.TUNNELLED;
} }
@Override @Override
@ -248,7 +248,7 @@ public final class RouteTracker implements RouteInfo, Cloneable {
@Override @Override
public boolean isLayered() { public boolean isLayered() {
return (this.layered == LayerType.LAYERED); return this.layered == LayerType.LAYERED;
} }
@Override @Override
@ -291,10 +291,10 @@ public final class RouteTracker implements RouteInfo, Cloneable {
final RouteTracker that = (RouteTracker) o; final RouteTracker that = (RouteTracker) o;
return return
// Do the cheapest checks first // Do the cheapest checks first
(this.connected == that.connected) && this.connected == that.connected &&
(this.secure == that.secure) && this.secure == that.secure &&
(this.tunnelled == that.tunnelled) && this.tunnelled == that.tunnelled &&
(this.layered == that.layered) && this.layered == that.layered &&
Objects.equals(this.targetHost, that.targetHost) && Objects.equals(this.targetHost, that.targetHost) &&
Objects.equals(this.localAddress, that.localAddress) && Objects.equals(this.localAddress, that.localAddress) &&
Objects.equals(this.proxyChain, that.proxyChain); Objects.equals(this.proxyChain, that.proxyChain);
@ -332,7 +332,7 @@ public final class RouteTracker implements RouteInfo, Cloneable {
*/ */
@Override @Override
public String toString() { public String toString() {
final StringBuilder cab = new StringBuilder(50 + getHopCount()*30); final StringBuilder cab = new StringBuilder(50 + getHopCount() * 30);
cab.append("RouteTracker["); cab.append("RouteTracker[");
if (this.localAddress != null) { if (this.localAddress != null) {

View File

@ -74,7 +74,7 @@ public class AuthScope {
final String schemeName) { final String schemeName) {
this.protocol = protocol != null ? protocol.toLowerCase(Locale.ROOT) : null; this.protocol = protocol != null ? protocol.toLowerCase(Locale.ROOT) : null;
this.host = host != null ? host.toLowerCase(Locale.ROOT) : null; this.host = host != null ? host.toLowerCase(Locale.ROOT) : null;
this.port = port >= 0 ? port: -1; this.port = port >= 0 ? port : -1;
this.realm = realm; this.realm = realm;
this.schemeName = schemeName != null ? schemeName.toUpperCase(Locale.ROOT) : null; this.schemeName = schemeName != null ? schemeName.toUpperCase(Locale.ROOT) : null;
} }

View File

@ -164,7 +164,9 @@ public interface Cookie {
/** /**
* Returns creation time of the cookie. * Returns creation time of the cookie.
*/ */
default Instant getCreationInstant() { return null; } default Instant getCreationInstant() {
return null;
}
/** /**
* Checks whether this Cookie has been marked as {@code httpOnly}. * Checks whether this Cookie has been marked as {@code httpOnly}.
@ -175,7 +177,7 @@ public interface Cookie {
* *
* @since 5.2 * @since 5.2
*/ */
default boolean isHttpOnly(){ default boolean isHttpOnly() {
return false; return false;
} }

View File

@ -112,7 +112,7 @@ public interface SetCookie extends Cookie {
* *
* @since 5.2 * @since 5.2
*/ */
default void setHttpOnly (final boolean httpOnly){ default void setHttpOnly(final boolean httpOnly) {
} }
} }

View File

@ -66,7 +66,7 @@ public class UrlEncodedFormEntity extends StringEntity {
* *
* @param parameters list of name/value pairs * @param parameters list of name/value pairs
*/ */
public UrlEncodedFormEntity (final List <? extends NameValuePair> parameters){ public UrlEncodedFormEntity(final List<? extends NameValuePair> parameters) {
this(parameters, null); this(parameters, null);
} }
@ -78,8 +78,8 @@ public class UrlEncodedFormEntity extends StringEntity {
* *
* @since 4.2 * @since 4.2
*/ */
public UrlEncodedFormEntity ( public UrlEncodedFormEntity(
final Iterable <? extends NameValuePair> parameters) { final Iterable<? extends NameValuePair> parameters) {
this(parameters, null); this(parameters, null);
} }

View File

@ -27,8 +27,8 @@
package org.apache.hc.client5.http.impl; package org.apache.hc.client5.http.impl;
import org.apache.hc.client5.http.cookie.StandardCookieSpec;
import org.apache.hc.client5.http.cookie.CookieSpecFactory; import org.apache.hc.client5.http.cookie.CookieSpecFactory;
import org.apache.hc.client5.http.cookie.StandardCookieSpec;
import org.apache.hc.client5.http.impl.cookie.IgnoreCookieSpecFactory; import org.apache.hc.client5.http.impl.cookie.IgnoreCookieSpecFactory;
import org.apache.hc.client5.http.impl.cookie.RFC6265CookieSpecFactory; import org.apache.hc.client5.http.impl.cookie.RFC6265CookieSpecFactory;
import org.apache.hc.client5.http.psl.PublicSuffixMatcher; import org.apache.hc.client5.http.psl.PublicSuffixMatcher;
@ -78,6 +78,7 @@ public final class CookieSpecSupport {
return createDefaultBuilder(publicSuffixMatcher).build(); return createDefaultBuilder(publicSuffixMatcher).build();
} }
private CookieSpecSupport() {} private CookieSpecSupport() {
}
} }

View File

@ -70,7 +70,7 @@ public class DefaultConnectionKeepAliveStrategy implements ConnectionKeepAliveSt
if (value != null && param.equalsIgnoreCase("timeout")) { if (value != null && param.equalsIgnoreCase("timeout")) {
try { try {
return TimeValue.ofSeconds(Long.parseLong(value)); return TimeValue.ofSeconds(Long.parseLong(value));
} catch(final NumberFormatException ignore) { } catch (final NumberFormatException ignore) {
} }
} }
} }

View File

@ -65,7 +65,7 @@ public final class IdleConnectionEvictor {
} }
} catch (final InterruptedException ex) { } catch (final InterruptedException ex) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} catch (final Exception ex) { } catch (final Exception ignore) {
} }
}); });

View File

@ -89,7 +89,7 @@ public class InMemoryDnsResolver implements DnsResolver {
if (LOG.isInfoEnabled()) { if (LOG.isInfoEnabled()) {
LOG.info("Resolving {} to {}", host, Arrays.deepToString(resolvedAddresses)); LOG.info("Resolving {} to {}", host, Arrays.deepToString(resolvedAddresses));
} }
if(resolvedAddresses == null){ if (resolvedAddresses == null) {
throw new UnknownHostException(host); throw new UnknownHostException(host);
} }
return resolvedAddresses; return resolvedAddresses;

View File

@ -91,7 +91,7 @@ public class Wire {
buffer.insert(0, header); buffer.insert(0, header);
log.debug("{} {}", this.id, buffer); log.debug("{} {}", this.id, buffer);
buffer.setLength(0); buffer.setLength(0);
} else if ((ch < 32) || (ch >= 127)) { } else if (ch < 32 || ch >= 127) {
buffer.append("[0x"); buffer.append("[0x");
buffer.append(Integer.toHexString(ch)); buffer.append(Integer.toHexString(ch));
buffer.append("]"); buffer.append("]");

View File

@ -975,7 +975,7 @@ public class H2AsyncClientBuilder {
} }
} catch (final InterruptedException ex) { } catch (final InterruptedException ex) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} catch (final Exception ex) { } catch (final Exception ignore) {
} }
}); });

View File

@ -474,8 +474,8 @@ public class DigestScheme implements AuthScheme, Serializable {
buffer.append(", "); buffer.append(", ");
} }
final String name = param.getName(); final String name = param.getName();
final boolean noQuotes = ("nc".equals(name) || "qop".equals(name) final boolean noQuotes = "nc".equals(name) || "qop".equals(name)
|| "algorithm".equals(name)); || "algorithm".equals(name);
BasicHeaderValueFormatter.INSTANCE.formatNameValuePair(buffer, param, !noQuotes); BasicHeaderValueFormatter.INSTANCE.formatNameValuePair(buffer, param, !noQuotes);
} }
return buffer.toString(); return buffer.toString();
@ -514,8 +514,8 @@ public class DigestScheme implements AuthScheme, Serializable {
final int n = binaryData.length; final int n = binaryData.length;
final char[] buffer = new char[n * 2]; final char[] buffer = new char[n * 2];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
final int low = (binaryData[i] & 0x0f); final int low = binaryData[i] & 0x0f;
final int high = ((binaryData[i] & 0xf0) >> 4); final int high = (binaryData[i] & 0xf0) >> 4;
buffer[i * 2] = HEXADECIMAL[high]; buffer[i * 2] = HEXADECIMAL[high];
buffer[(i * 2) + 1] = HEXADECIMAL[low]; buffer[(i * 2) + 1] = HEXADECIMAL[low];
} }

View File

@ -211,10 +211,10 @@ public abstract class GGSSchemeBase implements AuthScheme {
try { try {
final String authServer; final String authServer;
String hostname = host.getHostName(); String hostname = host.getHostName();
if (config.getUseCanonicalHostname() != org.apache.hc.client5.http.auth.KerberosConfig.Option.DISABLE){ if (config.getUseCanonicalHostname() != org.apache.hc.client5.http.auth.KerberosConfig.Option.DISABLE) {
try { try {
hostname = dnsResolver.resolveCanonicalHostname(host.getHostName()); hostname = dnsResolver.resolveCanonicalHostname(host.getHostName());
} catch (final UnknownHostException ignore){ } catch (final UnknownHostException ignore) {
} }
} }
if (config.getStripPort() != org.apache.hc.client5.http.auth.KerberosConfig.Option.DISABLE) { if (config.getStripPort() != org.apache.hc.client5.http.auth.KerberosConfig.Option.DISABLE) {

View File

@ -1224,7 +1224,7 @@ final class NTLMEngineImpl implements NTLMEngine {
} }
void buildMessage() { void buildMessage() {
throw new RuntimeException("Message builder not implemented for "+getClass().getName()); throw new RuntimeException("Message builder not implemented for " + getClass().getName());
} }
} }
@ -1241,7 +1241,7 @@ final class NTLMEngineImpl implements NTLMEngine {
Type1Message(final String domain, final String host, final Integer flags) { Type1Message(final String domain, final String host, final Integer flags) {
super(); super();
this.flags = ((flags == null)?getDefaultFlags(): flags.intValue()); this.flags = flags == null ? getDefaultFlags() : flags.intValue();
// See HTTPCLIENT-1662 // See HTTPCLIENT-1662
final String unqualifiedHost = host; final String unqualifiedHost = host;
@ -1541,7 +1541,7 @@ final class NTLMEngineImpl implements NTLMEngine {
try { try {
// This conditional may not work on Windows Server 2008 R2 and above, where it has not yet // This conditional may not work on Windows Server 2008 R2 and above, where it has not yet
// been tested // been tested
if (((type2Flags & FLAG_TARGETINFO_PRESENT) != 0) && if ((type2Flags & FLAG_TARGETINFO_PRESENT) != 0 &&
targetInformation != null && target != null) { targetInformation != null && target != null) {
// NTLMv2 // NTLMv2
ntResp = gen.getNTLMv2Response(); ntResp = gen.getNTLMv2Response();
@ -1621,7 +1621,7 @@ final class NTLMEngineImpl implements NTLMEngine {
final int lmRespLen = lmResp.length; final int lmRespLen = lmResp.length;
final int domainLen = domainBytes != null ? domainBytes.length : 0; final int domainLen = domainBytes != null ? domainBytes.length : 0;
final int hostLen = hostBytes != null ? hostBytes.length: 0; final int hostLen = hostBytes != null ? hostBytes.length : 0;
final int userLen = userBytes.length; final int userLen = userBytes.length;
final int sessionKeyLen; final int sessionKeyLen;
if (sessionKey != null) { if (sessionKey != null) {
@ -1808,26 +1808,26 @@ final class NTLMEngineImpl implements NTLMEngine {
} }
static int F(final int x, final int y, final int z) { static int F(final int x, final int y, final int z) {
return ((x & y) | (~x & z)); return (x & y) | (~x & z);
} }
static int G(final int x, final int y, final int z) { static int G(final int x, final int y, final int z) {
return ((x & y) | (x & z) | (y & z)); return (x & y) | (x & z) | (y & z);
} }
static int H(final int x, final int y, final int z) { static int H(final int x, final int y, final int z) {
return (x ^ y ^ z); return x ^ y ^ z;
} }
static int rotintlft(final int val, final int numbits) { static int rotintlft(final int val, final int numbits) {
return ((val << numbits) | (val >>> (32 - numbits))); return (val << numbits) | (val >>> (32 - numbits));
} }
static MessageDigest getMD5() { static MessageDigest getMD5() {
try { try {
return MessageDigest.getInstance("MD5"); return MessageDigest.getInstance("MD5");
} catch (final NoSuchAlgorithmException ex) { } catch (final NoSuchAlgorithmException ex) {
throw new RuntimeException("MD5 message digest doesn't seem to exist - fatal error: "+ex.getMessage(), ex); throw new RuntimeException("MD5 message digest doesn't seem to exist - fatal error: " + ex.getMessage(), ex);
} }
} }
@ -1929,70 +1929,70 @@ final class NTLMEngineImpl implements NTLMEngine {
} }
void round1(final int[] d) { void round1(final int[] d) {
A = rotintlft((A + F(B, C, D) + d[0]), 3); A = rotintlft(A + F(B, C, D) + d[0], 3);
D = rotintlft((D + F(A, B, C) + d[1]), 7); D = rotintlft(D + F(A, B, C) + d[1], 7);
C = rotintlft((C + F(D, A, B) + d[2]), 11); C = rotintlft(C + F(D, A, B) + d[2], 11);
B = rotintlft((B + F(C, D, A) + d[3]), 19); B = rotintlft(B + F(C, D, A) + d[3], 19);
A = rotintlft((A + F(B, C, D) + d[4]), 3); A = rotintlft(A + F(B, C, D) + d[4], 3);
D = rotintlft((D + F(A, B, C) + d[5]), 7); D = rotintlft(D + F(A, B, C) + d[5], 7);
C = rotintlft((C + F(D, A, B) + d[6]), 11); C = rotintlft(C + F(D, A, B) + d[6], 11);
B = rotintlft((B + F(C, D, A) + d[7]), 19); B = rotintlft(B + F(C, D, A) + d[7], 19);
A = rotintlft((A + F(B, C, D) + d[8]), 3); A = rotintlft(A + F(B, C, D) + d[8], 3);
D = rotintlft((D + F(A, B, C) + d[9]), 7); D = rotintlft(D + F(A, B, C) + d[9], 7);
C = rotintlft((C + F(D, A, B) + d[10]), 11); C = rotintlft(C + F(D, A, B) + d[10], 11);
B = rotintlft((B + F(C, D, A) + d[11]), 19); B = rotintlft(B + F(C, D, A) + d[11], 19);
A = rotintlft((A + F(B, C, D) + d[12]), 3); A = rotintlft(A + F(B, C, D) + d[12], 3);
D = rotintlft((D + F(A, B, C) + d[13]), 7); D = rotintlft(D + F(A, B, C) + d[13], 7);
C = rotintlft((C + F(D, A, B) + d[14]), 11); C = rotintlft(C + F(D, A, B) + d[14], 11);
B = rotintlft((B + F(C, D, A) + d[15]), 19); B = rotintlft(B + F(C, D, A) + d[15], 19);
} }
void round2(final int[] d) { void round2(final int[] d) {
A = rotintlft((A + G(B, C, D) + d[0] + 0x5a827999), 3); A = rotintlft(A + G(B, C, D) + d[0] + 0x5a827999, 3);
D = rotintlft((D + G(A, B, C) + d[4] + 0x5a827999), 5); D = rotintlft(D + G(A, B, C) + d[4] + 0x5a827999, 5);
C = rotintlft((C + G(D, A, B) + d[8] + 0x5a827999), 9); C = rotintlft(C + G(D, A, B) + d[8] + 0x5a827999, 9);
B = rotintlft((B + G(C, D, A) + d[12] + 0x5a827999), 13); B = rotintlft(B + G(C, D, A) + d[12] + 0x5a827999, 13);
A = rotintlft((A + G(B, C, D) + d[1] + 0x5a827999), 3); A = rotintlft(A + G(B, C, D) + d[1] + 0x5a827999, 3);
D = rotintlft((D + G(A, B, C) + d[5] + 0x5a827999), 5); D = rotintlft(D + G(A, B, C) + d[5] + 0x5a827999, 5);
C = rotintlft((C + G(D, A, B) + d[9] + 0x5a827999), 9); C = rotintlft(C + G(D, A, B) + d[9] + 0x5a827999, 9);
B = rotintlft((B + G(C, D, A) + d[13] + 0x5a827999), 13); B = rotintlft(B + G(C, D, A) + d[13] + 0x5a827999, 13);
A = rotintlft((A + G(B, C, D) + d[2] + 0x5a827999), 3); A = rotintlft(A + G(B, C, D) + d[2] + 0x5a827999, 3);
D = rotintlft((D + G(A, B, C) + d[6] + 0x5a827999), 5); D = rotintlft(D + G(A, B, C) + d[6] + 0x5a827999, 5);
C = rotintlft((C + G(D, A, B) + d[10] + 0x5a827999), 9); C = rotintlft(C + G(D, A, B) + d[10] + 0x5a827999, 9);
B = rotintlft((B + G(C, D, A) + d[14] + 0x5a827999), 13); B = rotintlft(B + G(C, D, A) + d[14] + 0x5a827999, 13);
A = rotintlft((A + G(B, C, D) + d[3] + 0x5a827999), 3); A = rotintlft(A + G(B, C, D) + d[3] + 0x5a827999, 3);
D = rotintlft((D + G(A, B, C) + d[7] + 0x5a827999), 5); D = rotintlft(D + G(A, B, C) + d[7] + 0x5a827999, 5);
C = rotintlft((C + G(D, A, B) + d[11] + 0x5a827999), 9); C = rotintlft(C + G(D, A, B) + d[11] + 0x5a827999, 9);
B = rotintlft((B + G(C, D, A) + d[15] + 0x5a827999), 13); B = rotintlft(B + G(C, D, A) + d[15] + 0x5a827999, 13);
} }
void round3(final int[] d) { void round3(final int[] d) {
A = rotintlft((A + H(B, C, D) + d[0] + 0x6ed9eba1), 3); A = rotintlft(A + H(B, C, D) + d[0] + 0x6ed9eba1, 3);
D = rotintlft((D + H(A, B, C) + d[8] + 0x6ed9eba1), 9); D = rotintlft(D + H(A, B, C) + d[8] + 0x6ed9eba1, 9);
C = rotintlft((C + H(D, A, B) + d[4] + 0x6ed9eba1), 11); C = rotintlft(C + H(D, A, B) + d[4] + 0x6ed9eba1, 11);
B = rotintlft((B + H(C, D, A) + d[12] + 0x6ed9eba1), 15); B = rotintlft(B + H(C, D, A) + d[12] + 0x6ed9eba1, 15);
A = rotintlft((A + H(B, C, D) + d[2] + 0x6ed9eba1), 3); A = rotintlft(A + H(B, C, D) + d[2] + 0x6ed9eba1, 3);
D = rotintlft((D + H(A, B, C) + d[10] + 0x6ed9eba1), 9); D = rotintlft(D + H(A, B, C) + d[10] + 0x6ed9eba1, 9);
C = rotintlft((C + H(D, A, B) + d[6] + 0x6ed9eba1), 11); C = rotintlft(C + H(D, A, B) + d[6] + 0x6ed9eba1, 11);
B = rotintlft((B + H(C, D, A) + d[14] + 0x6ed9eba1), 15); B = rotintlft(B + H(C, D, A) + d[14] + 0x6ed9eba1, 15);
A = rotintlft((A + H(B, C, D) + d[1] + 0x6ed9eba1), 3); A = rotintlft(A + H(B, C, D) + d[1] + 0x6ed9eba1, 3);
D = rotintlft((D + H(A, B, C) + d[9] + 0x6ed9eba1), 9); D = rotintlft(D + H(A, B, C) + d[9] + 0x6ed9eba1, 9);
C = rotintlft((C + H(D, A, B) + d[5] + 0x6ed9eba1), 11); C = rotintlft(C + H(D, A, B) + d[5] + 0x6ed9eba1, 11);
B = rotintlft((B + H(C, D, A) + d[13] + 0x6ed9eba1), 15); B = rotintlft(B + H(C, D, A) + d[13] + 0x6ed9eba1, 15);
A = rotintlft((A + H(B, C, D) + d[3] + 0x6ed9eba1), 3); A = rotintlft(A + H(B, C, D) + d[3] + 0x6ed9eba1, 3);
D = rotintlft((D + H(A, B, C) + d[11] + 0x6ed9eba1), 9); D = rotintlft(D + H(A, B, C) + d[11] + 0x6ed9eba1, 9);
C = rotintlft((C + H(D, A, B) + d[7] + 0x6ed9eba1), 11); C = rotintlft(C + H(D, A, B) + d[7] + 0x6ed9eba1, 11);
B = rotintlft((B + H(C, D, A) + d[15] + 0x6ed9eba1), 15); B = rotintlft(B + H(C, D, A) + d[15] + 0x6ed9eba1, 15);
} }

View File

@ -162,7 +162,7 @@ public class SystemDefaultCredentialsProvider implements CredentialsStore {
return new PasswordAuthentication(proxyUser, return new PasswordAuthentication(proxyUser,
proxyPassword != null ? proxyPassword.toCharArray() : new char[] {}); proxyPassword != null ? proxyPassword.toCharArray() : new char[] {});
} }
} catch (final NumberFormatException ex) { } catch (final NumberFormatException ignore) {
} }
return null; return null;

View File

@ -159,20 +159,22 @@ public final class ConnectExec implements ExecChainHandler {
LOG.debug("{} tunnel to target created.", exchangeId); LOG.debug("{} tunnel to target created.", exchangeId);
} }
tracker.tunnelTarget(false); tracker.tunnelTarget(false);
} break; }
break;
case HttpRouteDirector.TUNNEL_PROXY: { case HttpRouteDirector.TUNNEL_PROXY: {
// The most simple example for this case is a proxy chain // The most simple example for this case is a proxy chain
// of two proxies, where P1 must be tunnelled to P2. // of two proxies, where P1 must be tunnelled to P2.
// route: Source -> P1 -> P2 -> Target (3 hops) // route: Source -> P1 -> P2 -> Target (3 hops)
// fact: Source -> P1 -> Target (2 hops) // fact: Source -> P1 -> Target (2 hops)
final int hop = fact.getHopCount()-1; // the hop to establish final int hop = fact.getHopCount() - 1; // the hop to establish
final boolean secure = createTunnelToProxy(route, hop, context); final boolean secure = createTunnelToProxy(route, hop, context);
if (LOG.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
LOG.debug("{} tunnel to proxy created.", exchangeId); LOG.debug("{} tunnel to proxy created.", exchangeId);
} }
tracker.tunnelProxy(route.getHopTarget(hop), secure); tracker.tunnelProxy(route.getHopTarget(hop), secure);
} break; }
break;
case HttpRouteDirector.LAYER_PROTOCOL: case HttpRouteDirector.LAYER_PROTOCOL:
execRuntime.upgradeTls(context); execRuntime.upgradeTls(context);

View File

@ -112,7 +112,7 @@ public class FutureRequestExecutionService implements Closeable {
final HttpContext context, final HttpContext context,
final HttpClientResponseHandler<T> HttpClientResponseHandler, final HttpClientResponseHandler<T> HttpClientResponseHandler,
final FutureCallback<T> callback) { final FutureCallback<T> callback) {
if(closed.get()) { if (closed.get()) {
throw new IllegalStateException("Close has been called on this httpclient instance."); throw new IllegalStateException("Close has been called on this httpclient instance.");
} }
metrics.getScheduledConnections().incrementAndGet(); metrics.getScheduledConnections().incrementAndGet();

View File

@ -117,14 +117,14 @@ class InternalExecRuntime implements ExecRuntime, Cancellable {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("{} acquired endpoint {}", id, ConnPoolSupport.getId(connectionEndpoint)); log.debug("{} acquired endpoint {}", id, ConnPoolSupport.getId(connectionEndpoint));
} }
} catch(final TimeoutException ex) { } catch (final TimeoutException ex) {
connRequest.cancel(); connRequest.cancel();
throw new ConnectionRequestTimeoutException(ex.getMessage()); throw new ConnectionRequestTimeoutException(ex.getMessage());
} catch(final InterruptedException interrupted) { } catch (final InterruptedException interrupted) {
connRequest.cancel(); connRequest.cancel();
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
throw new RequestFailedException("Request aborted", interrupted); throw new RequestFailedException("Request aborted", interrupted);
} catch(final ExecutionException ex) { } catch (final ExecutionException ex) {
connRequest.cancel(); connRequest.cancel();
Throwable cause = ex.getCause(); Throwable cause = ex.getCause();
if (cause == null) { if (cause == null) {

View File

@ -118,7 +118,7 @@ public final class RedirectExec implements ExecChainHandler {
return response; return response;
} }
if (redirectCount >= maxRedirects) { if (redirectCount >= maxRedirects) {
throw new RedirectException("Maximum redirects ("+ maxRedirects + ") exceeded"); throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
} }
redirectCount++; redirectCount++;

View File

@ -190,7 +190,8 @@ class ResponseEntityProxy extends HttpEntityWrapper implements EofSensorWatcher
private static final class NullOutputStream extends OutputStream { private static final class NullOutputStream extends OutputStream {
private static final NullOutputStream INSTANCE = new NullOutputStream(); private static final NullOutputStream INSTANCE = new NullOutputStream();
private NullOutputStream() {} private NullOutputStream() {
}
@Override @Override
public void write(@SuppressWarnings("unused") final int byteValue) { public void write(@SuppressWarnings("unused") final int byteValue) {

View File

@ -159,7 +159,7 @@ public final class BasicClientCookie implements SetCookie, Cloneable, Serializab
*/ */
@Override @Override
public boolean isPersistent() { public boolean isPersistent() {
return (null != cookieExpiryDate); return null != cookieExpiryDate;
} }
@ -268,8 +268,8 @@ public final class BasicClientCookie implements SetCookie, Cloneable, Serializab
@Override @Override
public boolean isExpired(final Date date) { public boolean isExpired(final Date date) {
Args.notNull(date, "Date"); Args.notNull(date, "Date");
return (cookieExpiryDate != null return cookieExpiryDate != null
&& cookieExpiryDate.compareTo(DateUtils.toInstant(date)) <= 0); && cookieExpiryDate.compareTo(DateUtils.toInstant(date)) <= 0;
} }
/** /**
@ -281,8 +281,8 @@ public final class BasicClientCookie implements SetCookie, Cloneable, Serializab
@Override @Override
public boolean isExpired(final Instant instant) { public boolean isExpired(final Instant instant) {
Args.notNull(instant, "Instant"); Args.notNull(instant, "Instant");
return (cookieExpiryDate != null return cookieExpiryDate != null
&& cookieExpiryDate.compareTo(instant) <= 0); && cookieExpiryDate.compareTo(instant) <= 0;
} }
/** /**

View File

@ -132,7 +132,7 @@ public class BasicDomainHandler implements CommonCookieAttributeHandler {
if (host.equals(domain)) { if (host.equals(domain)) {
return true; return true;
} }
if ((cookie.containsAttribute(Cookie.DOMAIN_ATTR))) { if (cookie.containsAttribute(Cookie.DOMAIN_ATTR)) {
return domainMatch(domain, host); return domainMatch(domain, host);
} }
return false; return false;

View File

@ -139,7 +139,7 @@ public class LaxExpiresHandler extends AbstractCookieAttributeHandler implements
foundTime = true; foundTime = true;
hour = Integer.parseInt(matcher.group(1)); hour = Integer.parseInt(matcher.group(1));
minute = Integer.parseInt(matcher.group(2)); minute = Integer.parseInt(matcher.group(2));
second =Integer.parseInt(matcher.group(3)); second = Integer.parseInt(matcher.group(3));
continue; continue;
} }
} }

View File

@ -189,7 +189,8 @@ public class ManagedHttpClientConnectionFactory implements HttpConnectionFactory
private HttpMessageWriterFactory<ClassicHttpRequest> requestWriterFactory; private HttpMessageWriterFactory<ClassicHttpRequest> requestWriterFactory;
private HttpMessageParserFactory<ClassicHttpResponse> responseParserFactory; private HttpMessageParserFactory<ClassicHttpResponse> responseParserFactory;
private Builder() {} private Builder() {
}
public Builder http1Config(final Http1Config http1Config) { public Builder http1Config(final Http1Config http1Config) {
this.http1Config = http1Config; this.http1Config = http1Config;

View File

@ -443,7 +443,7 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
} }
final PoolEntry<HttpRoute, ManagedAsyncClientConnection> poolEntry = internalEndpoint.getPoolEntry(); final PoolEntry<HttpRoute, ManagedAsyncClientConnection> poolEntry = internalEndpoint.getPoolEntry();
final HttpRoute route = poolEntry.getRoute(); final HttpRoute route = poolEntry.getRoute();
final HttpHost firstHop = route.getProxyHost() != null ? route.getProxyHost(): route.getTargetHost(); final HttpHost firstHop = route.getProxyHost() != null ? route.getProxyHost() : route.getTargetHost();
final ConnectionConfig connectionConfig = resolveConnectionConfig(route); final ConnectionConfig connectionConfig = resolveConnectionConfig(route);
final Timeout connectTimeout = timeout != null ? timeout : connectionConfig.getConnectTimeout(); final Timeout connectTimeout = timeout != null ? timeout : connectionConfig.getConnectTimeout();
@ -638,7 +638,7 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
this.tlsConfigResolver = tlsConfigResolver; this.tlsConfigResolver = tlsConfigResolver;
} }
void closeIfExpired(final PoolEntry<HttpRoute, ManagedAsyncClientConnection > entry) { void closeIfExpired(final PoolEntry<HttpRoute, ManagedAsyncClientConnection> entry) {
final long now = System.currentTimeMillis(); final long now = System.currentTimeMillis();
if (entry.getExpiryDeadline().isBefore(now)) { if (entry.getExpiryDeadline().isBefore(now)) {
entry.discardConnection(CloseMode.GRACEFUL); entry.discardConnection(CloseMode.GRACEFUL);

View File

@ -65,7 +65,7 @@ public class BasicRouteDirector implements HttpRouteDirector {
int step = UNREACHABLE; int step = UNREACHABLE;
if ((fact == null) || (fact.getHopCount() < 1)) { if (fact == null || fact.getHopCount() < 1) {
step = firstStep(plan); step = firstStep(plan);
} else if (plan.getHopCount() > 1) { } else if (plan.getHopCount() > 1) {
step = proxiedStep(plan, fact); step = proxiedStep(plan, fact);
@ -122,9 +122,8 @@ public class BasicRouteDirector implements HttpRouteDirector {
} }
// Local address has to match only if the plan specifies one. // Local address has to match only if the plan specifies one.
if ((plan.getLocalAddress() != null) && if (plan.getLocalAddress() != null &&
!plan.getLocalAddress().equals(fact.getLocalAddress()) !plan.getLocalAddress().equals(fact.getLocalAddress())) {
) {
return UNREACHABLE; return UNREACHABLE;
} }
@ -155,7 +154,7 @@ public class BasicRouteDirector implements HttpRouteDirector {
return UNREACHABLE; return UNREACHABLE;
} }
for (int i=0; i<fhc-1; i++) { for (int i = 0; i < fhc - 1; i++) {
if (!plan.getHopTarget(i).equals(fact.getHopTarget(i))) { if (!plan.getHopTarget(i).equals(fact.getHopTarget(i))) {
return UNREACHABLE; return UNREACHABLE;
} }
@ -167,8 +166,8 @@ public class BasicRouteDirector implements HttpRouteDirector {
} }
// proxy chain and target are the same, check tunnelling and layering // proxy chain and target are the same, check tunnelling and layering
if ((fact.isTunnelled() && !plan.isTunnelled()) || if (fact.isTunnelled() && !plan.isTunnelled() ||
(fact.isLayered() && !plan.isLayered())) { fact.isLayered() && !plan.isLayered()) {
return UNREACHABLE; return UNREACHABLE;
} }

View File

@ -106,7 +106,7 @@ public class SystemDefaultRoutePlanner extends DefaultRoutePlanner {
private Proxy chooseProxy(final List<Proxy> proxies) { private Proxy chooseProxy(final List<Proxy> proxies) {
Proxy result = null; Proxy result = null;
// check the list for one we can use // check the list for one we can use
for (int i=0; (result == null) && (i < proxies.size()); i++) { for (int i = 0; result == null && i < proxies.size(); i++) {
final Proxy p = proxies.get(i); final Proxy p = proxies.get(i);
switch (p.type()) { switch (p.type()) {

View File

@ -82,7 +82,7 @@ public class RequestDefaultHeaders implements HttpRequestInterceptor {
if (this.defaultHeaders != null) { if (this.defaultHeaders != null) {
for (final Header defHeader : this.defaultHeaders) { for (final Header defHeader : this.defaultHeaders) {
if(!request.containsHeader(defHeader.getName())) { if (!request.containsHeader(defHeader.getName())) {
request.addHeader(defHeader); request.addHeader(defHeader);
} }
} }

View File

@ -71,7 +71,7 @@ public final class RoutingSupport {
return null; return null;
} }
if (host.getPort() < 0) { if (host.getPort() < 0) {
final int port = (schemePortResolver != null ? schemePortResolver: DefaultSchemePortResolver.INSTANCE).resolve(host); final int port = (schemePortResolver != null ? schemePortResolver : DefaultSchemePortResolver.INSTANCE).resolve(host);
if (port > 0) { if (port > 0) {
return new HttpHost(host.getSchemeName(), host.getAddress(), host.getHostName(), port); return new HttpHost(host.getSchemeName(), host.getAddress(), host.getHostName(), port);
} }

View File

@ -226,7 +226,7 @@ abstract class AbstractClientTlsStrategy implements TlsStrategy, TlsSocketStrate
if (supportedProtocols != null) { if (supportedProtocols != null) {
sslParameters.setProtocols(supportedProtocols); sslParameters.setProtocols(supportedProtocols);
} else { } else {
sslParameters.setProtocols((TLS.excludeWeak(upgradedSocket.getEnabledProtocols()))); sslParameters.setProtocols(TLS.excludeWeak(upgradedSocket.getEnabledProtocols()));
} }
if (supportedCipherSuites != null) { if (supportedCipherSuites != null) {
sslParameters.setCipherSuites(supportedCipherSuites); sslParameters.setCipherSuites(supportedCipherSuites);

View File

@ -114,7 +114,7 @@ final class DistinguishedNameParser {
dst.append(current); dst.append(current);
escaped = false; escaped = false;
} else { } else {
if ((delimiters != null && delimiters.test(current)) if (delimiters != null && delimiters.test(current)
|| Tokenizer.isWhitespace(current) || current == '\"') { || Tokenizer.isWhitespace(current) || current == '\"') {
break; break;
} else if (current == '\\') { } else if (current == '\\') {

View File

@ -328,7 +328,7 @@ public class SSLConnectionSocketFactory implements org.apache.hc.client5.http.so
if (supportedProtocols != null) { if (supportedProtocols != null) {
sslsock.setEnabledProtocols(supportedProtocols); sslsock.setEnabledProtocols(supportedProtocols);
} else { } else {
sslsock.setEnabledProtocols((TLS.excludeWeak(sslsock.getEnabledProtocols()))); sslsock.setEnabledProtocols(TLS.excludeWeak(sslsock.getEnabledProtocols()));
} }
if (supportedCipherSuites != null) { if (supportedCipherSuites != null) {
sslsock.setEnabledCipherSuites(supportedCipherSuites); sslsock.setEnabledCipherSuites(supportedCipherSuites);

View File

@ -126,8 +126,8 @@ public final class ByteArrayBuilder {
if (b == null) { if (b == null) {
return this; return this;
} }
if ((off < 0) || (off > b.length) || (len < 0) || if (off < 0 || off > b.length || len < 0 ||
((off + len) < 0) || ((off + len) > b.length)) { off + len < 0 || off + len > b.length) {
throw new IndexOutOfBoundsException("off: " + off + " len: " + len + " b.length: " + b.length); throw new IndexOutOfBoundsException("off: " + off + " len: " + len + " b.length: " + b.length);
} }
ensureFreeCapacity(len); ensureFreeCapacity(len);
@ -154,8 +154,8 @@ public final class ByteArrayBuilder {
if (b == null) { if (b == null) {
return this; return this;
} }
if ((off < 0) || (off > b.length) || (len < 0) || if (off < 0 || off > b.length || len < 0 ||
((off + len) < 0) || ((off + len) > b.length)) { off + len < 0 || off + len > b.length) {
throw new IndexOutOfBoundsException("off: " + off + " len: " + len + " b.length: " + b.length); throw new IndexOutOfBoundsException("off: " + off + " len: " + len + " b.length: " + b.length);
} }
return append(CharBuffer.wrap(b, off, len)); return append(CharBuffer.wrap(b, off, len));

View File

@ -347,7 +347,7 @@ class TestHttpRoute {
Assertions.assertThrows(IllegalArgumentException.class, () -> route.getHopTarget(1)); Assertions.assertThrows(IllegalArgumentException.class, () -> route.getHopTarget(1));
Assertions.assertThrows(IllegalArgumentException.class, () -> route.getHopTarget(-1)); Assertions.assertThrows(IllegalArgumentException.class, () -> route.getHopTarget(-1));
final HttpHost[] proxies2 = new HttpHost[]{ PROXY3 }; final HttpHost[] proxies2 = new HttpHost[]{PROXY3};
final HttpRoute route2 = new HttpRoute(TARGET1, LOCAL62, proxies2, false, final HttpRoute route2 = new HttpRoute(TARGET1, LOCAL62, proxies2, false,
TunnelType.TUNNELLED, LayerType.PLAIN); TunnelType.TUNNELLED, LayerType.PLAIN);
Assertions.assertEquals(2, route2.getHopCount(), "B: hop count"); Assertions.assertEquals(2, route2.getHopCount(), "B: hop count");
@ -356,13 +356,13 @@ class TestHttpRoute {
Assertions.assertThrows(IllegalArgumentException.class, () -> route2.getHopTarget(2)); Assertions.assertThrows(IllegalArgumentException.class, () -> route2.getHopTarget(2));
Assertions.assertThrows(IllegalArgumentException.class, () -> route2.getHopTarget(-2)); Assertions.assertThrows(IllegalArgumentException.class, () -> route2.getHopTarget(-2));
final HttpHost[] proxies3 = new HttpHost[]{ PROXY3, PROXY1, PROXY2 }; final HttpHost[] proxies3 = new HttpHost[]{PROXY3, PROXY1, PROXY2};
final HttpRoute route3 = new HttpRoute(TARGET1, LOCAL42, proxies3, false, final HttpRoute route3 = new HttpRoute(TARGET1, LOCAL42, proxies3, false,
TunnelType.PLAIN, LayerType.LAYERED); TunnelType.PLAIN, LayerType.LAYERED);
Assertions.assertEquals(4, route3.getHopCount(), "C: hop count"); Assertions.assertEquals(4, route3.getHopCount(), "C: hop count");
Assertions.assertEquals(PROXY3 , route3.getHopTarget(0), "C: hop 0"); Assertions.assertEquals(PROXY3, route3.getHopTarget(0), "C: hop 0");
Assertions.assertEquals(PROXY1 , route3.getHopTarget(1), "C: hop 1"); Assertions.assertEquals(PROXY1, route3.getHopTarget(1), "C: hop 1");
Assertions.assertEquals(PROXY2 , route3.getHopTarget(2), "C: hop 2"); Assertions.assertEquals(PROXY2, route3.getHopTarget(2), "C: hop 2");
Assertions.assertEquals(TARGET1, route3.getHopTarget(3), "C: hop 3"); Assertions.assertEquals(TARGET1, route3.getHopTarget(3), "C: hop 3");
Assertions.assertThrows(IllegalArgumentException.class, () -> route3.getHopTarget(4)); Assertions.assertThrows(IllegalArgumentException.class, () -> route3.getHopTarget(4));
Assertions.assertThrows(IllegalArgumentException.class, () -> route3.getHopTarget(Integer.MIN_VALUE)); Assertions.assertThrows(IllegalArgumentException.class, () -> route3.getHopTarget(Integer.MIN_VALUE));

View File

@ -64,7 +64,7 @@ class TestCredentials {
Assertions.assertEquals(new NTUserPrincipal("DOMAIN", "name"), Assertions.assertEquals(new NTUserPrincipal("DOMAIN", "name"),
creds1.getUserPrincipal()); creds1.getUserPrincipal());
Assertions.assertArrayEquals("pwd".toCharArray(), creds1.getPassword()); Assertions.assertArrayEquals("pwd".toCharArray(), creds1.getPassword());
Assertions.assertEquals("[principal: DOMAIN\\name][workstation: "+ creds1.getWorkstation() +"][netbiosDomain: DOMAIN]", Assertions.assertEquals("[principal: DOMAIN\\name][workstation: " + creds1.getWorkstation() + "][netbiosDomain: DOMAIN]",
creds1.toString()); creds1.toString());
final NTCredentials creds2 = new NTCredentials( final NTCredentials creds2 = new NTCredentials(
"name", null, null, null); "name", null, null, null);
@ -72,7 +72,7 @@ class TestCredentials {
Assertions.assertEquals(new NTUserPrincipal(null, "name"), Assertions.assertEquals(new NTUserPrincipal(null, "name"),
creds2.getUserPrincipal()); creds2.getUserPrincipal());
Assertions.assertNull(creds2.getPassword()); Assertions.assertNull(creds2.getPassword());
Assertions.assertEquals("[principal: name][workstation: "+creds1.getWorkstation() +"][netbiosDomain: null]", Assertions.assertEquals("[principal: name][workstation: " + creds1.getWorkstation() + "][netbiosDomain: null]",
creds2.toString()); creds2.toString());
} }

View File

@ -37,9 +37,10 @@ class FormBodyPartTest {
@Test @Test
void testConstructorCompat() throws Exception { void testConstructorCompat() throws Exception {
final File tmp= File.createTempFile("test", "test"); final File tmp = File.createTempFile("test", "test");
tmp.deleteOnExit(); tmp.deleteOnExit();
final FileBody obj = new FileBody(tmp, ContentType.APPLICATION_OCTET_STREAM); final FileBody obj = new FileBody(tmp, ContentType.APPLICATION_OCTET_STREAM);
Assertions.assertEquals(tmp.getName(), obj.getFilename()); Assertions.assertEquals(tmp.getName(), obj.getFilename());
} }
} }

View File

@ -58,7 +58,6 @@ public class AsyncClientConnectionConfig {
final PoolingAsyncClientConnectionManager cm = PoolingAsyncClientConnectionManagerBuilder.create() final PoolingAsyncClientConnectionManager cm = PoolingAsyncClientConnectionManagerBuilder.create()
.setConnectionConfigResolver(route -> { .setConnectionConfigResolver(route -> {
// Use different settings for all secure (TLS) connections // Use different settings for all secure (TLS) connections
final HttpHost targetHost = route.getTargetHost();
if (route.isSecure()) { if (route.isSecure()) {
return ConnectionConfig.custom() return ConnectionConfig.custom()
.setConnectTimeout(Timeout.ofMinutes(2)) .setConnectTimeout(Timeout.ofMinutes(2))

View File

@ -52,7 +52,6 @@ public class ClientConnectionConfig {
final PoolingHttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create() final PoolingHttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
.setConnectionConfigResolver(route -> { .setConnectionConfigResolver(route -> {
// Use different settings for all secure (TLS) connections // Use different settings for all secure (TLS) connections
final HttpHost targetHost = route.getTargetHost();
if (route.isSecure()) { if (route.isSecure()) {
return ConnectionConfig.custom() return ConnectionConfig.custom()
.setConnectTimeout(Timeout.ofMinutes(2)) .setConnectTimeout(Timeout.ofMinutes(2))

View File

@ -296,10 +296,10 @@ class TestDigestScheme {
void testDigestAuthenticationMD5Sess() throws Exception { void testDigestAuthenticationMD5Sess() throws Exception {
// Example using Digest auth with MD5-sess // Example using Digest auth with MD5-sess
final String realm="realm"; final String realm = "realm";
final String username="username"; final String username = "username";
final String password="password"; final String password = "password";
final String nonce="e273f1776275974f1a120d8b92c5b3cb"; final String nonce = "e273f1776275974f1a120d8b92c5b3cb";
final HttpRequest request = new BasicHttpRequest("Simple", "/"); final HttpRequest request = new BasicHttpRequest("Simple", "/");
final HttpHost host = new HttpHost("somehost", 80); final HttpHost host = new HttpHost("somehost", 80);
@ -307,7 +307,7 @@ class TestDigestScheme {
.add(new AuthScope(host, realm, null), username, password.toCharArray()) .add(new AuthScope(host, realm, null), username, password.toCharArray())
.build(); .build();
final String challenge=StandardAuthScheme.DIGEST + " realm=\"" + realm + "\", " final String challenge = StandardAuthScheme.DIGEST + " realm=\"" + realm + "\", "
+ "nonce=\"" + nonce + "\", " + "nonce=\"" + nonce + "\", "
+ "opaque=\"SomeString\", " + "opaque=\"SomeString\", "
+ "stale=false, " + "stale=false, "
@ -331,7 +331,7 @@ class TestDigestScheme {
Assertions.assertEquals("MD5-sess", table.get("algorithm")); Assertions.assertEquals("MD5-sess", table.get("algorithm"));
Assertions.assertEquals("/", table.get("uri")); Assertions.assertEquals("/", table.get("uri"));
Assertions.assertEquals(nonce, table.get("nonce")); Assertions.assertEquals(nonce, table.get("nonce"));
Assertions.assertEquals(1, Integer.parseInt(table.get("nc"),16)); Assertions.assertEquals(1, Integer.parseInt(table.get("nc"), 16));
Assertions.assertNotNull(table.get("cnonce")); Assertions.assertNotNull(table.get("cnonce"));
Assertions.assertEquals("SomeString", table.get("opaque")); Assertions.assertEquals("SomeString", table.get("opaque"));
Assertions.assertEquals("auth", table.get("qop")); Assertions.assertEquals("auth", table.get("qop"));
@ -346,10 +346,10 @@ class TestDigestScheme {
void testDigestAuthenticationMD5SessNoQop() throws Exception { void testDigestAuthenticationMD5SessNoQop() throws Exception {
// Example using Digest auth with MD5-sess // Example using Digest auth with MD5-sess
final String realm="realm"; final String realm = "realm";
final String username="username"; final String username = "username";
final String password="password"; final String password = "password";
final String nonce="e273f1776275974f1a120d8b92c5b3cb"; final String nonce = "e273f1776275974f1a120d8b92c5b3cb";
final HttpRequest request = new BasicHttpRequest("Simple", "/"); final HttpRequest request = new BasicHttpRequest("Simple", "/");
final HttpHost host = new HttpHost("somehost", 80); final HttpHost host = new HttpHost("somehost", 80);
@ -357,7 +357,7 @@ class TestDigestScheme {
.add(new AuthScope(host, realm, null), username, password.toCharArray()) .add(new AuthScope(host, realm, null), username, password.toCharArray())
.build(); .build();
final String challenge=StandardAuthScheme.DIGEST + " realm=\"" + realm + "\", " final String challenge = StandardAuthScheme.DIGEST + " realm=\"" + realm + "\", "
+ "nonce=\"" + nonce + "\", " + "nonce=\"" + nonce + "\", "
+ "opaque=\"SomeString\", " + "opaque=\"SomeString\", "
+ "stale=false, " + "stale=false, "
@ -390,10 +390,10 @@ class TestDigestScheme {
void testDigestAuthenticationMD5SessUnknownQop() throws Exception { void testDigestAuthenticationMD5SessUnknownQop() throws Exception {
// Example using Digest auth with MD5-sess // Example using Digest auth with MD5-sess
final String realm="realm"; final String realm = "realm";
final String username="username"; final String username = "username";
final String password="password"; final String password = "password";
final String nonce="e273f1776275974f1a120d8b92c5b3cb"; final String nonce = "e273f1776275974f1a120d8b92c5b3cb";
final HttpRequest request = new BasicHttpRequest("Simple", "/"); final HttpRequest request = new BasicHttpRequest("Simple", "/");
final HttpHost host = new HttpHost("somehost", 80); final HttpHost host = new HttpHost("somehost", 80);
@ -401,7 +401,7 @@ class TestDigestScheme {
.add(new AuthScope(host, realm, null), username, password.toCharArray()) .add(new AuthScope(host, realm, null), username, password.toCharArray())
.build(); .build();
final String challenge=StandardAuthScheme.DIGEST + " realm=\"" + realm + "\", " final String challenge = StandardAuthScheme.DIGEST + " realm=\"" + realm + "\", "
+ "nonce=\"" + nonce + "\", " + "nonce=\"" + nonce + "\", "
+ "opaque=\"SomeString\", " + "opaque=\"SomeString\", "
+ "stale=false, " + "stale=false, "
@ -425,10 +425,10 @@ class TestDigestScheme {
void testDigestAuthenticationUnknownAlgo() throws Exception { void testDigestAuthenticationUnknownAlgo() throws Exception {
// Example using Digest auth with MD5-sess // Example using Digest auth with MD5-sess
final String realm="realm"; final String realm = "realm";
final String username="username"; final String username = "username";
final String password="password"; final String password = "password";
final String nonce="e273f1776275974f1a120d8b92c5b3cb"; final String nonce = "e273f1776275974f1a120d8b92c5b3cb";
final HttpRequest request = new BasicHttpRequest("Simple", "/"); final HttpRequest request = new BasicHttpRequest("Simple", "/");
final HttpHost host = new HttpHost("somehost", 80); final HttpHost host = new HttpHost("somehost", 80);
@ -436,7 +436,7 @@ class TestDigestScheme {
.add(new AuthScope(host, realm, null), username, password.toCharArray()) .add(new AuthScope(host, realm, null), username, password.toCharArray())
.build(); .build();
final String challenge=StandardAuthScheme.DIGEST + " realm=\"" + realm + "\", " final String challenge = StandardAuthScheme.DIGEST + " realm=\"" + realm + "\", "
+ "nonce=\"" + nonce + "\", " + "nonce=\"" + nonce + "\", "
+ "opaque=\"SomeString\", " + "opaque=\"SomeString\", "
+ "stale=false, " + "stale=false, "
@ -594,12 +594,12 @@ class TestDigestScheme {
digester.write(0xe4); digester.write(0xe4);
digester.write(0xf6); digester.write(0xf6);
digester.write(0xfc); digester.write(0xfc);
digester.write(new byte[] { 'a', 'b', 'c'}); digester.write(new byte[]{'a', 'b', 'c'});
Assertions.assertNull(digester.getDigest()); Assertions.assertNull(digester.getDigest());
digester.close(); digester.close();
Assertions.assertEquals("acd2b59cd01c7737d8069015584c6cac", DigestScheme.formatHex(digester.getDigest())); Assertions.assertEquals("acd2b59cd01c7737d8069015584c6cac", DigestScheme.formatHex(digester.getDigest()));
Assertions.assertThrows(IOException.class, () -> digester.write('a')); Assertions.assertThrows(IOException.class, () -> digester.write('a'));
Assertions.assertThrows(IOException.class, () -> digester.write(new byte[] { 'a', 'b', 'c'})); Assertions.assertThrows(IOException.class, () -> digester.write(new byte[]{'a', 'b', 'c'}));
} }
@Test @Test
@ -658,7 +658,7 @@ class TestDigestScheme {
@Test @Test
void testDigestAuthenticationQopAuthOrAuthIntNonRepeatableEntity() throws Exception { void testDigestAuthenticationQopAuthOrAuthIntNonRepeatableEntity() throws Exception {
final ClassicHttpRequest request = new BasicClassicHttpRequest("Post", "/"); final ClassicHttpRequest request = new BasicClassicHttpRequest("Post", "/");
request.setEntity(new InputStreamEntity(new ByteArrayInputStream(new byte[] {'a'}), -1, ContentType.DEFAULT_TEXT)); request.setEntity(new InputStreamEntity(new ByteArrayInputStream(new byte[]{'a'}), -1, ContentType.DEFAULT_TEXT));
final HttpHost host = new HttpHost("somehost", 80); final HttpHost host = new HttpHost("somehost", 80);
final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create() final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
.add(new AuthScope(host, "realm1", null), "username", "password".toCharArray()) .add(new AuthScope(host, "realm1", null), "username", "password".toCharArray())
@ -705,7 +705,7 @@ class TestDigestScheme {
@Test @Test
void testDigestAuthenticationQopIntOnlyNonRepeatableEntity() throws Exception { void testDigestAuthenticationQopIntOnlyNonRepeatableEntity() throws Exception {
final ClassicHttpRequest request = new BasicClassicHttpRequest("Post", "/"); final ClassicHttpRequest request = new BasicClassicHttpRequest("Post", "/");
request.setEntity(new InputStreamEntity(new ByteArrayInputStream(new byte[] {'a'}), -1, ContentType.DEFAULT_TEXT)); request.setEntity(new InputStreamEntity(new ByteArrayInputStream(new byte[]{'a'}), -1, ContentType.DEFAULT_TEXT));
final HttpHost host = new HttpHost("somehost", 80); final HttpHost host = new HttpHost("somehost", 80);
final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create() final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
.add(new AuthScope(host, "realm1", null), "username", "password".toCharArray()) .add(new AuthScope(host, "realm1", null), "username", "password".toCharArray())
@ -768,7 +768,7 @@ class TestDigestScheme {
// Generate expected userhash // Generate expected userhash
final MessageDigest md = MessageDigest.getInstance("MD5"); final MessageDigest md = MessageDigest.getInstance("MD5");
md.update(("username:realm1").getBytes(StandardCharsets.UTF_8)); md.update("username:realm1".getBytes(StandardCharsets.UTF_8));
final String expectedUserhash = bytesToHex(md.digest()); final String expectedUserhash = bytesToHex(md.digest());
Assertions.assertEquals(expectedUserhash, table.get("username")); Assertions.assertEquals(expectedUserhash, table.get("username"));
@ -819,6 +819,7 @@ class TestDigestScheme {
final String response = table.get("response"); final String response = table.get("response");
Assertions.assertNotNull(response); Assertions.assertNotNull(response);
} }
@Test @Test
void testDigestAuthenticationWithInvalidUsernameAndValidUsernameStar() throws Exception { void testDigestAuthenticationWithInvalidUsernameAndValidUsernameStar() throws Exception {
final ClassicHttpRequest request = new BasicClassicHttpRequest("POST", "/"); final ClassicHttpRequest request = new BasicClassicHttpRequest("POST", "/");

View File

@ -252,7 +252,7 @@ class TestNTLMEngineImpl {
"me", "mypassword", "myhost", "mydomain".toCharArray(), "me", "mypassword", "myhost", "mydomain".toCharArray(),
toBytes("0001020304050607"), toBytes("0001020304050607"),
0xffffffff, 0xffffffff,
null,null).getBytes(); null, null).getBytes();
checkArraysMatch(toBytes("4E544C4D53535000030000001800180048000000180018006000000004000400780000000C000C007C0000001400140088000000100010009C000000FFFFFFFF0501280A0000000FA86886A5D297814200000000000000000000000000000000EEC7568E00798491244959B9C942F4F367C5CBABEEF546F74D0045006D00790068006F00730074006D007900700061007300730077006F007200640094DDAB1EBB82C9A1AB914CAE6F199644"), checkArraysMatch(toBytes("4E544C4D53535000030000001800180048000000180018006000000004000400780000000C000C007C0000001400140088000000100010009C000000FFFFFFFF0501280A0000000FA86886A5D297814200000000000000000000000000000000EEC7568E00798491244959B9C942F4F367C5CBABEEF546F74D0045006D00790068006F00730074006D007900700061007300730077006F007200640094DDAB1EBB82C9A1AB914CAE6F199644"),
bytes); bytes);
final byte[] bytes2 = new NTLMEngineImpl.Type3Message( final byte[] bytes2 = new NTLMEngineImpl.Type3Message(
@ -268,21 +268,21 @@ class TestNTLMEngineImpl {
} }
private static final String cannedCert = private static final String cannedCert =
"-----BEGIN CERTIFICATE-----\n"+ "-----BEGIN CERTIFICATE-----\n" +
"MIIDIDCCAgigAwIBAgIEOqKaWTANBgkqhkiG9w0BAQsFADBSMQswCQYDVQQGEwJVUzEQMA4GA1UEBxMH\n"+ "MIIDIDCCAgigAwIBAgIEOqKaWTANBgkqhkiG9w0BAQsFADBSMQswCQYDVQQGEwJVUzEQMA4GA1UEBxMH\n" +
"TXkgQ2l0eTEYMBYGA1UEChMPTXkgT3JnYW5pemF0aW9uMRcwFQYDVQQDEw5NeSBBcHBsaWNhdGlvbjAe\n"+ "TXkgQ2l0eTEYMBYGA1UEChMPTXkgT3JnYW5pemF0aW9uMRcwFQYDVQQDEw5NeSBBcHBsaWNhdGlvbjAe\n" +
"Fw0xNzAzMTcxNDAyMzRaFw0yNzAzMTUxNDAyMzRaMFIxCzAJBgNVBAYTAlVTMRAwDgYDVQQHEwdNeSBD\n"+ "Fw0xNzAzMTcxNDAyMzRaFw0yNzAzMTUxNDAyMzRaMFIxCzAJBgNVBAYTAlVTMRAwDgYDVQQHEwdNeSBD\n" +
"aXR5MRgwFgYDVQQKEw9NeSBPcmdhbml6YXRpb24xFzAVBgNVBAMTDk15IEFwcGxpY2F0aW9uMIIBIjAN\n"+ "aXR5MRgwFgYDVQQKEw9NeSBPcmdhbml6YXRpb24xFzAVBgNVBAMTDk15IEFwcGxpY2F0aW9uMIIBIjAN\n" +
"BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArc+mbViBaHeRSt82KrJ5IF+62b/Qob95Lca4DJIislTY\n"+ "BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArc+mbViBaHeRSt82KrJ5IF+62b/Qob95Lca4DJIislTY\n" +
"vLPIo0R1faBV8BkEeUQwo01srkf3RaGLCHNZnFal4KEzbtiUy6W+n08G5E9w9YG+WSwW2dmjvEI7k2a2\n"+ "vLPIo0R1faBV8BkEeUQwo01srkf3RaGLCHNZnFal4KEzbtiUy6W+n08G5E9w9YG+WSwW2dmjvEI7k2a2\n" +
"xqlaM4NdMKL4ONPXcxfZsMDqxDgpdkaNPKpZ10NDq6rmBTkQw/OSG0z1KLtwLkF1ZQ/3mXdjVzvP83V2\n"+ "xqlaM4NdMKL4ONPXcxfZsMDqxDgpdkaNPKpZ10NDq6rmBTkQw/OSG0z1KLtwLkF1ZQ/3mXdjVzvP83V2\n" +
"g17AqBazb0Z1YHsVKmkGjPqnq3niJH/6Oke4N+5k/1cE5lSJcQNGP0nqeGdJfvqQZ+gk6gH/sOngZL9X\n"+ "g17AqBazb0Z1YHsVKmkGjPqnq3niJH/6Oke4N+5k/1cE5lSJcQNGP0nqeGdJfvqQZ+gk6gH/sOngZL9X\n" +
"hPVkpseAwHa+xuPneDSjibLgLmMt3XGDK6jGfjdp5FWqFvAD5E3LHbW9gwIDAQABMA0GCSqGSIb3DQEB\n"+ "hPVkpseAwHa+xuPneDSjibLgLmMt3XGDK6jGfjdp5FWqFvAD5E3LHbW9gwIDAQABMA0GCSqGSIb3DQEB\n" +
"CwUAA4IBAQCpUXUHhl5LyMSO5Q0OktEc9AaFjZtVfknpPde6Zeh35Pqd2354ErvJSBWgzFAphda0oh2s\n"+ "CwUAA4IBAQCpUXUHhl5LyMSO5Q0OktEc9AaFjZtVfknpPde6Zeh35Pqd2354ErvJSBWgzFAphda0oh2s\n" +
"OIAFkM6LJQEnVDTbXDXN+YY8e3gb9ryfh85hkhC0XI9qp17WPSkmw8XgDfvRd6YQgKm1AnLxjOCwG2jg\n"+ "OIAFkM6LJQEnVDTbXDXN+YY8e3gb9ryfh85hkhC0XI9qp17WPSkmw8XgDfvRd6YQgKm1AnLxjOCwG2jg\n" +
"i09iZBIWkW3ZeRAMvWPHHjvq44iZB5ZrEl0apgumS6MxpUzKOr5Pcq0jxJDw2UCj5YloFMNl+UINv2vV\n"+ "i09iZBIWkW3ZeRAMvWPHHjvq44iZB5ZrEl0apgumS6MxpUzKOr5Pcq0jxJDw2UCj5YloFMNl+UINv2vV\n" +
"aL/DR6ivc61dOfN1E/VNBGkkCk/AogNyucGiFMCq9hd25Y9EbkBBqObYTH1XMX+ufsJh+6hG7KDQ1e/F\n"+ "aL/DR6ivc61dOfN1E/VNBGkkCk/AogNyucGiFMCq9hd25Y9EbkBBqObYTH1XMX+ufsJh+6hG7KDQ1e/F\n" +
"nRrlhKwM2uRe+aSH0D6/erjDBT7tXvwn\n"+ "nRrlhKwM2uRe+aSH0D6/erjDBT7tXvwn\n" +
"-----END CERTIFICATE-----"; "-----END CERTIFICATE-----";
@Test @Test
@ -318,9 +318,9 @@ class TestNTLMEngineImpl {
/* Byte array check helper */ /* Byte array check helper */
static void checkArraysMatch(final byte[] a1, final byte[] a2) { static void checkArraysMatch(final byte[] a1, final byte[] a2) {
Assertions.assertEquals(a1.length,a2.length); Assertions.assertEquals(a1.length, a2.length);
for (int i = 0; i < a1.length; i++) { for (int i = 0; i < a1.length; i++) {
Assertions.assertEquals(a1[i],a2[i]); Assertions.assertEquals(a1[i], a2[i]);
} }
} }

View File

@ -79,8 +79,8 @@ class TestDefaultBackoffStrategy {
@Test @Test
void doesNotBackOffForNon429And503StatusCodes() { void doesNotBackOffForNon429And503StatusCodes() {
for(int i = 100; i <= 599; i++) { for (int i = 100; i <= 599; i++) {
if (i== HttpStatus.SC_TOO_MANY_REQUESTS || i == HttpStatus.SC_SERVICE_UNAVAILABLE) { if (i == HttpStatus.SC_TOO_MANY_REQUESTS || i == HttpStatus.SC_SERVICE_UNAVAILABLE) {
continue; continue;
} }
final HttpResponse resp = new BasicHttpResponse(i, "Foo"); final HttpResponse resp = new BasicHttpResponse(i, "Foo");

View File

@ -77,7 +77,8 @@ class TestResponseEntityProxy {
final HttpEntity wrappedEntity = httpEntityArgumentCaptor.getValue(); final HttpEntity wrappedEntity = httpEntityArgumentCaptor.getValue();
final InputStream is = wrappedEntity.getContent(); final InputStream is = wrappedEntity.getContent();
while (is.read() != -1) {} // read until the end while (is.read() != -1) {
} // read until the end
final Supplier<List<? extends Header>> trailers = wrappedEntity.getTrailers(); final Supplier<List<? extends Header>> trailers = wrappedEntity.getTrailers();
Assertions.assertTrue(trailers.get().isEmpty()); Assertions.assertTrue(trailers.get().isEmpty());
@ -98,7 +99,8 @@ class TestResponseEntityProxy {
final HttpEntity wrappedEntity = httpEntityArgumentCaptor.getValue(); final HttpEntity wrappedEntity = httpEntityArgumentCaptor.getValue();
final InputStream is = wrappedEntity.getContent(); final InputStream is = wrappedEntity.getContent();
while (is.read() != -1) {} // consume the stream so it can reach to trailers and parse while (is.read() != -1) {
} // consume the stream so it can reach to trailers and parse
final Supplier<List<? extends Header>> trailers = wrappedEntity.getTrailers(); final Supplier<List<? extends Header>> trailers = wrappedEntity.getTrailers();
final List<? extends Header> headers = trailers.get(); final List<? extends Header> headers = trailers.get();

View File

@ -43,20 +43,15 @@ import org.junit.jupiter.api.Test;
class TestRouteDirector { class TestRouteDirector {
// a selection of constants for generating routes // a selection of constants for generating routes
public final static public final static HttpHost TARGET1 = new HttpHost("target1.test.invalid", 80);
HttpHost TARGET1 = new HttpHost("target1.test.invalid", 80); public final static HttpHost TARGET2 = new HttpHost("target2.test.invalid", 8080);
public final static
HttpHost TARGET2 = new HttpHost("target2.test.invalid", 8080);
// It is not necessary to have extra targets for https. // It is not necessary to have extra targets for https.
// The 'layered' and 'secure' flags are specified explicitly // The 'layered' and 'secure' flags are specified explicitly
// for routes, they will not be determined from the scheme. // for routes, they will not be determined from the scheme.
public final static public final static HttpHost PROXY1 = new HttpHost("proxy1.test.invalid", 80);
HttpHost PROXY1 = new HttpHost("proxy1.test.invalid", 80); public final static HttpHost PROXY2 = new HttpHost("proxy2.test.invalid", 1080);
public final static public final static HttpHost PROXY3 = new HttpHost("proxy3.test.invalid", 88);
HttpHost PROXY2 = new HttpHost("proxy2.test.invalid", 1080);
public final static
HttpHost PROXY3 = new HttpHost("proxy3.test.invalid", 88);
public final static InetAddress LOCAL41; public final static InetAddress LOCAL41;
public final static InetAddress LOCAL42; public final static InetAddress LOCAL42;
@ -66,8 +61,8 @@ class TestRouteDirector {
// need static initializer to deal with exceptions // need static initializer to deal with exceptions
static { static {
try { try {
LOCAL41 = InetAddress.getByAddress(new byte[]{ 127, 0, 0, 1 }); LOCAL41 = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
LOCAL42 = InetAddress.getByAddress(new byte[]{ 127, 0, 0, 2 }); LOCAL42 = InetAddress.getByAddress(new byte[]{127, 0, 0, 2});
LOCAL61 = InetAddress.getByAddress(new byte[]{ LOCAL61 = InetAddress.getByAddress(new byte[]{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
@ -156,9 +151,9 @@ class TestRouteDirector {
@Test @Test
void testProxyChain() { void testProxyChain() {
final HttpHost[] chainA = { PROXY1 }; final HttpHost[] chainA = {PROXY1};
final HttpHost[] chainB = { PROXY1, PROXY2 }; final HttpHost[] chainB = {PROXY1, PROXY2};
final HttpHost[] chainC = { PROXY2, PROXY1 }; final HttpHost[] chainC = {PROXY2, PROXY1};
final HttpRouteDirector rowdy = BasicRouteDirector.INSTANCE; final HttpRouteDirector rowdy = BasicRouteDirector.INSTANCE;
final HttpRoute route1cA = new HttpRoute(TARGET1, null, chainA, false, final HttpRoute route1cA = new HttpRoute(TARGET1, null, chainA, false,
@ -278,7 +273,6 @@ class TestRouteDirector {
Assertions.assertEquals(HttpRouteDirector.UNREACHABLE, step, "unreachable route 1s from 1u not detected"); Assertions.assertEquals(HttpRouteDirector.UNREACHABLE, step, "unreachable route 1s from 1u not detected");
step = rowdy.nextStep(route1s, route1p1u); step = rowdy.nextStep(route1s, route1p1u);
Assertions.assertEquals(HttpRouteDirector.UNREACHABLE, step, "unreachable route 1s from 1p1u not detected"); Assertions.assertEquals(HttpRouteDirector.UNREACHABLE, step, "unreachable route 1s from 1p1u not detected");
@ -349,7 +343,6 @@ class TestRouteDirector {
Assertions.assertEquals(HttpRouteDirector.COMPLETE, step, "complete route1tls not detected"); Assertions.assertEquals(HttpRouteDirector.COMPLETE, step, "complete route1tls not detected");
step = rowdy.nextStep(route1, route1t); step = rowdy.nextStep(route1, route1t);
Assertions.assertEquals(HttpRouteDirector.UNREACHABLE, step, "unreachable route1 from 1t not detected"); Assertions.assertEquals(HttpRouteDirector.UNREACHABLE, step, "unreachable route1 from 1t not detected");

View File

@ -47,20 +47,15 @@ import org.junit.jupiter.api.Test;
class TestRouteTracker { class TestRouteTracker {
// a selection of constants for generating routes // a selection of constants for generating routes
public final static public final static HttpHost TARGET1 = new HttpHost("target1.test.invalid", 80);
HttpHost TARGET1 = new HttpHost("target1.test.invalid", 80); public final static HttpHost TARGET2 = new HttpHost("target2.test.invalid", 8080);
public final static
HttpHost TARGET2 = new HttpHost("target2.test.invalid", 8080);
// It is not necessary to have extra targets for https. // It is not necessary to have extra targets for https.
// The 'layered' and 'secure' flags are specified explicitly // The 'layered' and 'secure' flags are specified explicitly
// for routes, they will not be determined from the scheme. // for routes, they will not be determined from the scheme.
public final static public final static HttpHost PROXY1 = new HttpHost("proxy1.test.invalid", 80);
HttpHost PROXY1 = new HttpHost("proxy1.test.invalid", 80); public final static HttpHost PROXY2 = new HttpHost("proxy2.test.invalid", 1080);
public final static public final static HttpHost PROXY3 = new HttpHost("proxy3.test.invalid", 88);
HttpHost PROXY2 = new HttpHost("proxy2.test.invalid", 1080);
public final static
HttpHost PROXY3 = new HttpHost("proxy3.test.invalid", 88);
public final static InetAddress LOCAL41; public final static InetAddress LOCAL41;
public final static InetAddress LOCAL42; public final static InetAddress LOCAL42;
@ -70,8 +65,8 @@ class TestRouteTracker {
// need static initializer to deal with exceptions // need static initializer to deal with exceptions
static { static {
try { try {
LOCAL41 = InetAddress.getByAddress(new byte[]{ 127, 0, 0, 1 }); LOCAL41 = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
LOCAL42 = InetAddress.getByAddress(new byte[]{ 127, 0, 0, 2 }); LOCAL42 = InetAddress.getByAddress(new byte[]{127, 0, 0, 2});
LOCAL61 = InetAddress.getByAddress(new byte[]{ LOCAL61 = InetAddress.getByAddress(new byte[]{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
@ -235,7 +230,7 @@ class TestRouteTracker {
Assertions.assertTrue(complete, "incomplete route 1"); Assertions.assertTrue(complete, "incomplete route 1");
// tunnelled, but neither secure nor layered // tunnelled, but neither secure nor layered
proxies = new HttpHost[]{ PROXY3, PROXY2 }; proxies = new HttpHost[]{PROXY3, PROXY2};
r = new HttpRoute(TARGET1, null, proxies, false, r = new HttpRoute(TARGET1, null, proxies, false,
TunnelType.TUNNELLED, LayerType.PLAIN); TunnelType.TUNNELLED, LayerType.PLAIN);
rt = new RouteTracker(r); rt = new RouteTracker(r);
@ -243,7 +238,7 @@ class TestRouteTracker {
Assertions.assertTrue(complete, "incomplete route 2"); Assertions.assertTrue(complete, "incomplete route 2");
// tunnelled, layered, but not secure // tunnelled, layered, but not secure
proxies = new HttpHost[]{ PROXY3, PROXY2, PROXY1 }; proxies = new HttpHost[]{PROXY3, PROXY2, PROXY1};
r = new HttpRoute(TARGET2, LOCAL61, proxies, false, r = new HttpRoute(TARGET2, LOCAL61, proxies, false,
TunnelType.TUNNELLED, LayerType.LAYERED); TunnelType.TUNNELLED, LayerType.LAYERED);
rt = new RouteTracker(r); rt = new RouteTracker(r);
@ -251,7 +246,7 @@ class TestRouteTracker {
Assertions.assertTrue(complete, "incomplete route 3"); Assertions.assertTrue(complete, "incomplete route 3");
// tunnelled, layered, secure // tunnelled, layered, secure
proxies = new HttpHost[]{ PROXY1, PROXY3 }; proxies = new HttpHost[]{PROXY1, PROXY3};
r = new HttpRoute(TARGET1, LOCAL61, proxies, true, r = new HttpRoute(TARGET1, LOCAL61, proxies, true,
TunnelType.TUNNELLED, LayerType.LAYERED); TunnelType.TUNNELLED, LayerType.LAYERED);
rt = new RouteTracker(r); rt = new RouteTracker(r);
@ -438,7 +433,7 @@ class TestRouteTracker {
// check that all toString are OK and different // check that all toString are OK and different
final Set<String> rtstrings = new HashSet<>(); final Set<String> rtstrings = new HashSet<>();
for (final RouteTracker current: hs) { for (final RouteTracker current : hs) {
final String rts = checkToString(current); final String rts = checkToString(current);
Assertions.assertTrue(rtstrings.add(rts), "duplicate toString: " + rts); Assertions.assertTrue(rtstrings.add(rts), "duplicate toString: " + rts);
} }
@ -480,7 +475,7 @@ class TestRouteTracker {
boolean complete = false; boolean complete = false;
int n = steps; int n = steps;
while (!complete && (n > 0)) { while (!complete && n > 0) {
final int action = rd.nextStep(r, rt.toRoute()); final int action = rd.nextStep(r, rt.toRoute());
switch (action) { switch (action) {
@ -494,19 +489,21 @@ class TestRouteTracker {
final boolean sec = r.isSecure(); final boolean sec = r.isSecure();
rt.connectTarget(sec); rt.connectTarget(sec);
checkCTLS(rt, true, false, false, sec); checkCTLS(rt, true, false, false, sec);
Assertions.assertEquals(1, rt.getHopCount(), "wrong hop count "+msg); Assertions.assertEquals(1, rt.getHopCount(), "wrong hop count " + msg);
Assertions.assertEquals(r.getTargetHost(), rt.getHopTarget(0), "wrong hop0 "+msg); Assertions.assertEquals(r.getTargetHost(), rt.getHopTarget(0), "wrong hop0 " + msg);
} break; }
break;
case HttpRouteDirector.CONNECT_PROXY: { case HttpRouteDirector.CONNECT_PROXY: {
// we assume an insecure proxy connection // we assume an insecure proxy connection
final boolean sec = false; final boolean sec = false;
rt.connectProxy(r.getProxyHost(), sec); rt.connectProxy(r.getProxyHost(), sec);
checkCTLS(rt, true, false, false, sec); checkCTLS(rt, true, false, false, sec);
Assertions.assertEquals(2, rt.getHopCount(), "wrong hop count "+msg); Assertions.assertEquals(2, rt.getHopCount(), "wrong hop count " + msg);
Assertions.assertEquals(r.getProxyHost(), rt.getHopTarget(0), "wrong hop0 "+msg); Assertions.assertEquals(r.getProxyHost(), rt.getHopTarget(0), "wrong hop0 " + msg);
Assertions.assertEquals(r.getTargetHost(), rt.getHopTarget(1), "wrong hop1 "+msg); Assertions.assertEquals(r.getTargetHost(), rt.getHopTarget(1), "wrong hop1 " + msg);
} break; }
break;
case HttpRouteDirector.TUNNEL_TARGET: { case HttpRouteDirector.TUNNEL_TARGET: {
final int hops = rt.getHopCount(); final int hops = rt.getHopCount();
@ -514,25 +511,27 @@ class TestRouteTracker {
final boolean sec = false; final boolean sec = false;
rt.tunnelTarget(sec); rt.tunnelTarget(sec);
checkCTLS(rt, true, true, false, sec); checkCTLS(rt, true, true, false, sec);
Assertions.assertEquals(hops, rt.getHopCount(), "wrong hop count "+msg); Assertions.assertEquals(hops, rt.getHopCount(), "wrong hop count " + msg);
Assertions.assertEquals(r.getProxyHost(), rt.getHopTarget(0), "wrong hop0 "+msg); Assertions.assertEquals(r.getProxyHost(), rt.getHopTarget(0), "wrong hop0 " + msg);
Assertions.assertEquals(r.getTargetHost(), rt.getHopTarget(hops-1), "wrong hopN "+msg); Assertions.assertEquals(r.getTargetHost(), rt.getHopTarget(hops - 1), "wrong hopN " + msg);
} break; }
break;
case HttpRouteDirector.TUNNEL_PROXY: { case HttpRouteDirector.TUNNEL_PROXY: {
final int hops = rt.getHopCount(); // before tunnelling final int hops = rt.getHopCount(); // before tunnelling
// we assume an insecure tunnel // we assume an insecure tunnel
final boolean sec = false; final boolean sec = false;
final HttpHost pxy = r.getHopTarget(hops-1); final HttpHost pxy = r.getHopTarget(hops - 1);
rt.tunnelProxy(pxy, sec); rt.tunnelProxy(pxy, sec);
// Since we're tunnelling to a proxy and not the target, // Since we're tunnelling to a proxy and not the target,
// the 'tunelling' flag is false: no end-to-end tunnel. // the 'tunelling' flag is false: no end-to-end tunnel.
checkCTLS(rt, true, false, false, sec); checkCTLS(rt, true, false, false, sec);
Assertions.assertEquals(hops+1, rt.getHopCount(), "wrong hop count "+msg); Assertions.assertEquals(hops + 1, rt.getHopCount(), "wrong hop count " + msg);
Assertions.assertEquals(r.getProxyHost(), rt.getHopTarget(0), "wrong hop0 "+msg); Assertions.assertEquals(r.getProxyHost(), rt.getHopTarget(0), "wrong hop0 " + msg);
Assertions.assertEquals(pxy, rt.getHopTarget(hops-1), "wrong hop"+hops+" "+msg); Assertions.assertEquals(pxy, rt.getHopTarget(hops - 1), "wrong hop" + hops + " " + msg);
Assertions.assertEquals(r.getTargetHost(), rt.getHopTarget(hops), "wrong hopN "+msg); Assertions.assertEquals(r.getTargetHost(), rt.getHopTarget(hops), "wrong hopN " + msg);
} break; }
break;
case HttpRouteDirector.LAYER_PROTOCOL: { case HttpRouteDirector.LAYER_PROTOCOL: {
final int hops = rt.getHopCount(); final int hops = rt.getHopCount();
@ -540,15 +539,16 @@ class TestRouteTracker {
final boolean sec = r.isSecure(); final boolean sec = r.isSecure();
rt.layerProtocol(sec); rt.layerProtocol(sec);
checkCTLS(rt, true, tun, true, sec); checkCTLS(rt, true, tun, true, sec);
Assertions.assertEquals(hops, rt.getHopCount(), "wrong hop count "+msg); Assertions.assertEquals(hops, rt.getHopCount(), "wrong hop count " + msg);
Assertions.assertEquals(r.getProxyHost(), rt.getProxyHost(), "wrong proxy "+msg); Assertions.assertEquals(r.getProxyHost(), rt.getProxyHost(), "wrong proxy " + msg);
Assertions.assertEquals(r.getTargetHost(), rt.getTargetHost(), "wrong target "+msg); Assertions.assertEquals(r.getTargetHost(), rt.getTargetHost(), "wrong target " + msg);
} break; }
break;
// UNREACHABLE // UNREACHABLE
default: default:
Assertions.fail("unexpected action " + action + " from director, "+msg); Assertions.fail("unexpected action " + action + " from director, " + msg);
break; break;
} // switch } // switch
@ -578,7 +578,7 @@ class TestRouteTracker {
Assertions.assertTrue(rts.contains(las), "no local address in toString(): " + rts); Assertions.assertTrue(rts.contains(las), "no local address in toString(): " + rts);
} }
for (int i=0; i<rt.getHopCount(); i++) { for (int i = 0; i < rt.getHopCount(); i++) {
final String hts = rt.getHopTarget(i).toString(); final String hts = rt.getHopTarget(i).toString();
Assertions.assertTrue(rts.contains(hts), "hop " + i + " (" + hts + ") missing in toString(): " + rts); Assertions.assertTrue(rts.contains(hts), "hop " + i + " (" + hts + ") missing in toString(): " + rts);
} }

View File

@ -34,10 +34,11 @@ import org.junit.jupiter.api.Test;
/** /**
* Tests {@link PublicSuffixMatcherLoader}. * Tests {@link PublicSuffixMatcherLoader}.
*/ */
public class TestPublicSuffixMatcherLoader { class TestPublicSuffixMatcherLoader {
@Test @Test
public void testGetDefault() { void testGetDefault() {
assertNotNull(PublicSuffixMatcherLoader.getDefault()); assertNotNull(PublicSuffixMatcherLoader.getDefault());
} }
} }

View File

@ -43,10 +43,10 @@ import org.apache.hc.core5.reactor.ssl.TlsDetails;
import org.apache.hc.core5.ssl.SSLContexts; import org.apache.hc.core5.ssl.SSLContexts;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
public class AbstractClientTlsStrategyTest { class AbstractClientTlsStrategyTest {
@Test @Test
public void testToEscapedString_withControlCharacters() { void testToEscapedString_withControlCharacters() {
// Create a X500Principal with control characters // Create a X500Principal with control characters
final X500Principal principal = new X500Principal("CN=Test\b\bName\n,O=TestOrg"); final X500Principal principal = new X500Principal("CN=Test\b\bName\n,O=TestOrg");
@ -75,7 +75,7 @@ public class AbstractClientTlsStrategyTest {
} }
@Test @Test
public void testVerifySession_escapedPeerAndIssuer() throws Exception { void testVerifySession_escapedPeerAndIssuer() throws Exception {
// Mock SSLSession and X509Certificate // Mock SSLSession and X509Certificate
final SSLSession mockSession = mock(SSLSession.class); final SSLSession mockSession = mock(SSLSession.class);
final X509Certificate mockCert = mock(X509Certificate.class); final X509Certificate mockCert = mock(X509Certificate.class);

View File

@ -300,24 +300,24 @@ class TestDefaultHostnameVerifier {
String domain; String domain;
// Unknown // Unknown
domain = "dev.b.cloud.a"; domain = "dev.b.cloud.a";
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity( "service.apps." + domain, "*.apps." + domain)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity("service.apps." + domain, "*.apps." + domain));
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict( "service.apps." + domain, "*.apps." + domain)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict("service.apps." + domain, "*.apps." + domain));
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher));
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher));
// ICANN // ICANN
domain = "dev.b.cloud.com"; domain = "dev.b.cloud.com";
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity( "service.apps." + domain, "*.apps." + domain)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity("service.apps." + domain, "*.apps." + domain));
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict( "service.apps." + domain, "*.apps." + domain)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict("service.apps." + domain, "*.apps." + domain));
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher));
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher));
// PRIVATE // PRIVATE
domain = "dev.b.cloud.lan"; domain = "dev.b.cloud.lan";
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity( "service.apps." + domain, "*.apps." + domain)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity("service.apps." + domain, "*.apps." + domain));
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict( "service.apps." + domain, "*.apps." + domain)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict("service.apps." + domain, "*.apps." + domain));
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher));
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher));
} }
@Test @Test
@ -325,18 +325,18 @@ class TestDefaultHostnameVerifier {
String domain; String domain;
// Unknown // Unknown
domain = "dev.b.cloud.a"; domain = "dev.b.cloud.a";
Assertions.assertFalse(DefaultHostnameVerifier.matchIdentity( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.ICANN)); Assertions.assertFalse(DefaultHostnameVerifier.matchIdentity("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.ICANN));
Assertions.assertFalse(DefaultHostnameVerifier.matchIdentityStrict( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.ICANN)); Assertions.assertFalse(DefaultHostnameVerifier.matchIdentityStrict("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.ICANN));
// ICANN // ICANN
domain = "dev.b.cloud.com"; domain = "dev.b.cloud.com";
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.ICANN)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.ICANN));
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.ICANN)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.ICANN));
// PRIVATE // PRIVATE
domain = "dev.b.cloud.lan"; domain = "dev.b.cloud.lan";
Assertions.assertFalse(DefaultHostnameVerifier.matchIdentity( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.ICANN)); Assertions.assertFalse(DefaultHostnameVerifier.matchIdentity("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.ICANN));
Assertions.assertFalse(DefaultHostnameVerifier.matchIdentityStrict( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.ICANN)); Assertions.assertFalse(DefaultHostnameVerifier.matchIdentityStrict("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.ICANN));
} }
@Test @Test
@ -344,18 +344,18 @@ class TestDefaultHostnameVerifier {
String domain; String domain;
// Unknown // Unknown
domain = "dev.b.cloud.a"; domain = "dev.b.cloud.a";
Assertions.assertFalse(DefaultHostnameVerifier.matchIdentity( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.PRIVATE)); Assertions.assertFalse(DefaultHostnameVerifier.matchIdentity("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.PRIVATE));
Assertions.assertFalse(DefaultHostnameVerifier.matchIdentityStrict( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.PRIVATE)); Assertions.assertFalse(DefaultHostnameVerifier.matchIdentityStrict("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.PRIVATE));
// ICANN // ICANN
domain = "dev.b.cloud.com"; domain = "dev.b.cloud.com";
Assertions.assertFalse(DefaultHostnameVerifier.matchIdentity( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.PRIVATE)); Assertions.assertFalse(DefaultHostnameVerifier.matchIdentity("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.PRIVATE));
Assertions.assertFalse(DefaultHostnameVerifier.matchIdentityStrict( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.PRIVATE)); Assertions.assertFalse(DefaultHostnameVerifier.matchIdentityStrict("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.PRIVATE));
// PRIVATE // PRIVATE
domain = "dev.b.cloud.lan"; domain = "dev.b.cloud.lan";
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.PRIVATE)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.PRIVATE));
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.PRIVATE)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.PRIVATE));
} }
@Test @Test
@ -363,22 +363,23 @@ class TestDefaultHostnameVerifier {
String domain; String domain;
// Unknown // Unknown
domain = "dev.b.cloud.a"; domain = "dev.b.cloud.a";
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.UNKNOWN)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.UNKNOWN));
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.UNKNOWN)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.UNKNOWN));
// ICANN // ICANN
domain = "dev.b.cloud.com"; domain = "dev.b.cloud.com";
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.UNKNOWN)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.UNKNOWN));
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.UNKNOWN)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.UNKNOWN));
// PRIVATE // PRIVATE
domain = "dev.b.cloud.lan"; domain = "dev.b.cloud.lan";
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.UNKNOWN)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentity("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.UNKNOWN));
Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict( "service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.UNKNOWN)); Assertions.assertTrue(DefaultHostnameVerifier.matchIdentityStrict("service.apps." + domain, "*.apps." + domain, publicSuffixMatcher, DomainType.UNKNOWN));
} }
@Test // Check compressed IPv6 hostname matching // Check compressed IPv6 hostname matching
void testHTTPCLIENT_1316() throws Exception{ @Test
void testHTTPCLIENT_1316() throws Exception {
final String host1 = "2001:0db8:aaaa:bbbb:cccc:0:0:0001"; final String host1 = "2001:0db8:aaaa:bbbb:cccc:0:0:0001";
DefaultHostnameVerifier.matchIPv6Address(host1, Collections.singletonList(SubjectName.IP("2001:0db8:aaaa:bbbb:cccc:0:0:0001"))); DefaultHostnameVerifier.matchIPv6Address(host1, Collections.singletonList(SubjectName.IP("2001:0db8:aaaa:bbbb:cccc:0:0:0001")));
DefaultHostnameVerifier.matchIPv6Address(host1, Collections.singletonList(SubjectName.IP("2001:0db8:aaaa:bbbb:cccc::1"))); DefaultHostnameVerifier.matchIPv6Address(host1, Collections.singletonList(SubjectName.IP("2001:0db8:aaaa:bbbb:cccc::1")));

View File

@ -219,6 +219,14 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId> <artifactId>maven-checkstyle-plugin</artifactId>
<version>3.3.1</version>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>hc-stylecheck</artifactId>
<version>3</version>
</dependency>
</dependencies>
<executions> <executions>
<execution> <execution>
<id>validate-main</id> <id>validate-main</id>