Convert control statement bodies to block.
git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@1433390 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
parent
2c0be950d8
commit
917145dbd3
|
@ -161,7 +161,9 @@ class BasicHttpCache implements HttpCache {
|
|||
return false;
|
||||
}
|
||||
Header hdr = resp.getFirstHeader(HTTP.CONTENT_LEN);
|
||||
if (hdr == null) return false;
|
||||
if (hdr == null) {
|
||||
return false;
|
||||
}
|
||||
int contentLength;
|
||||
try {
|
||||
contentLength = Integer.parseInt(hdr.getValue());
|
||||
|
@ -281,10 +283,16 @@ class BasicHttpCache implements HttpCache {
|
|||
|
||||
public HttpCacheEntry getCacheEntry(HttpHost host, HttpRequest request) throws IOException {
|
||||
HttpCacheEntry root = storage.getEntry(uriExtractor.getURI(host, request));
|
||||
if (root == null) return null;
|
||||
if (!root.hasVariants()) return root;
|
||||
if (root == null) {
|
||||
return null;
|
||||
}
|
||||
if (!root.hasVariants()) {
|
||||
return root;
|
||||
}
|
||||
String variantCacheKey = root.getVariantMap().get(uriExtractor.getVariantKey(request, root));
|
||||
if (variantCacheKey == null) return null;
|
||||
if (variantCacheKey == null) {
|
||||
return null;
|
||||
}
|
||||
return storage.getEntry(variantCacheKey);
|
||||
}
|
||||
|
||||
|
@ -297,7 +305,9 @@ class BasicHttpCache implements HttpCache {
|
|||
throws IOException {
|
||||
Map<String,Variant> variants = new HashMap<String,Variant>();
|
||||
HttpCacheEntry root = storage.getEntry(uriExtractor.getURI(host, request));
|
||||
if (root == null || !root.hasVariants()) return variants;
|
||||
if (root == null || !root.hasVariants()) {
|
||||
return variants;
|
||||
}
|
||||
for(Map.Entry<String, String> variant : root.getVariantMap().entrySet()) {
|
||||
String variantKey = variant.getKey();
|
||||
String variantCacheKey = variant.getValue();
|
||||
|
@ -310,9 +320,13 @@ class BasicHttpCache implements HttpCache {
|
|||
String variantCacheKey, Map<String, Variant> variants)
|
||||
throws IOException {
|
||||
HttpCacheEntry entry = storage.getEntry(variantCacheKey);
|
||||
if (entry == null) return;
|
||||
if (entry == null) {
|
||||
return;
|
||||
}
|
||||
Header etagHeader = entry.getFirstHeader(HeaderConstants.ETAG);
|
||||
if (etagHeader == null) return;
|
||||
if (etagHeader == null) {
|
||||
return;
|
||||
}
|
||||
variants.put(etagHeader.getValue(), new Variant(variantKey, variantCacheKey, entry));
|
||||
}
|
||||
|
||||
|
|
|
@ -134,7 +134,9 @@ class CacheInvalidator {
|
|||
|
||||
protected void flushUriIfSameHost(URL requestURL, URL targetURL) {
|
||||
URL canonicalTarget = getAbsoluteURL(cacheKeyGenerator.canonicalizeUri(targetURL.toString()));
|
||||
if (canonicalTarget == null) return;
|
||||
if (canonicalTarget == null) {
|
||||
return;
|
||||
}
|
||||
if (canonicalTarget.getAuthority().equalsIgnoreCase(requestURL.getAuthority())) {
|
||||
flushEntry(canonicalTarget.toString());
|
||||
}
|
||||
|
@ -142,14 +144,18 @@ class CacheInvalidator {
|
|||
|
||||
protected void flushRelativeUriFromSameHost(URL reqURL, String relUri) {
|
||||
URL relURL = getRelativeURL(reqURL, relUri);
|
||||
if (relURL == null) return;
|
||||
if (relURL == null) {
|
||||
return;
|
||||
}
|
||||
flushUriIfSameHost(reqURL, relURL);
|
||||
}
|
||||
|
||||
|
||||
protected boolean flushAbsoluteUriFromSameHost(URL reqURL, String uri) {
|
||||
URL absURL = getAbsoluteURL(uri);
|
||||
if (absURL == null) return false;
|
||||
if (absURL == null) {
|
||||
return false;
|
||||
}
|
||||
flushUriIfSameHost(reqURL,absURL);
|
||||
return true;
|
||||
}
|
||||
|
@ -190,30 +196,46 @@ class CacheInvalidator {
|
|||
public void flushInvalidatedCacheEntries(HttpHost host,
|
||||
HttpRequest request, HttpResponse response) {
|
||||
int status = response.getStatusLine().getStatusCode();
|
||||
if (status < 200 || status > 299) return;
|
||||
if (status < 200 || status > 299) {
|
||||
return;
|
||||
}
|
||||
URL reqURL = getAbsoluteURL(cacheKeyGenerator.getURI(host, request));
|
||||
if (reqURL == null) return;
|
||||
if (reqURL == null) {
|
||||
return;
|
||||
}
|
||||
URL canonURL = getContentLocationURL(reqURL, response);
|
||||
if (canonURL == null) return;
|
||||
if (canonURL == null) {
|
||||
return;
|
||||
}
|
||||
String cacheKey = cacheKeyGenerator.canonicalizeUri(canonURL.toString());
|
||||
HttpCacheEntry entry = getEntry(cacheKey);
|
||||
if (entry == null) return;
|
||||
if (entry == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// do not invalidate if response is strictly older than entry
|
||||
// or if the etags match
|
||||
|
||||
if (responseDateOlderThanEntryDate(response, entry)) return;
|
||||
if (!responseAndEntryEtagsDiffer(response, entry)) return;
|
||||
if (responseDateOlderThanEntryDate(response, entry)) {
|
||||
return;
|
||||
}
|
||||
if (!responseAndEntryEtagsDiffer(response, entry)) {
|
||||
return;
|
||||
}
|
||||
|
||||
flushUriIfSameHost(reqURL, canonURL);
|
||||
}
|
||||
|
||||
private URL getContentLocationURL(URL reqURL, HttpResponse response) {
|
||||
Header clHeader = response.getFirstHeader("Content-Location");
|
||||
if (clHeader == null) return null;
|
||||
if (clHeader == null) {
|
||||
return null;
|
||||
}
|
||||
String contentLocation = clHeader.getValue();
|
||||
URL canonURL = getAbsoluteURL(contentLocation);
|
||||
if (canonURL != null) return canonURL;
|
||||
if (canonURL != null) {
|
||||
return canonURL;
|
||||
}
|
||||
return getRelativeURL(reqURL, contentLocation);
|
||||
}
|
||||
|
||||
|
@ -221,7 +243,9 @@ class CacheInvalidator {
|
|||
HttpCacheEntry entry) {
|
||||
Header entryEtag = entry.getFirstHeader(HeaderConstants.ETAG);
|
||||
Header responseEtag = response.getFirstHeader(HeaderConstants.ETAG);
|
||||
if (entryEtag == null || responseEtag == null) return false;
|
||||
if (entryEtag == null || responseEtag == null) {
|
||||
return false;
|
||||
}
|
||||
return (!entryEtag.getValue().equals(responseEtag.getValue()));
|
||||
}
|
||||
|
||||
|
|
|
@ -74,7 +74,9 @@ class CacheKeyGenerator {
|
|||
String hostname = u.getHost().toLowerCase();
|
||||
int port = canonicalizePort(u.getPort(), protocol);
|
||||
String path = canonicalizePath(u.getPath());
|
||||
if ("".equals(path)) path = "/";
|
||||
if ("".equals(path)) {
|
||||
path = "/";
|
||||
}
|
||||
String query = u.getQuery();
|
||||
String file = (query != null) ? (path + "?" + query) : path;
|
||||
URL out = new URL(protocol, hostname, port, file);
|
||||
|
@ -109,8 +111,9 @@ class CacheKeyGenerator {
|
|||
}
|
||||
|
||||
protected String getFullHeaderValue(Header[] headers) {
|
||||
if (headers == null)
|
||||
return "";
|
||||
if (headers == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
StringBuilder buf = new StringBuilder("");
|
||||
boolean first = true;
|
||||
|
@ -136,7 +139,9 @@ class CacheKeyGenerator {
|
|||
* @return String the extracted variant URI
|
||||
*/
|
||||
public String getVariantURI(HttpHost host, HttpRequest req, HttpCacheEntry entry) {
|
||||
if (!entry.hasVariants()) return getURI(host, req);
|
||||
if (!entry.hasVariants()) {
|
||||
return getURI(host, req);
|
||||
}
|
||||
return getVariantKey(req, entry) + getURI(host, req);
|
||||
}
|
||||
|
||||
|
|
|
@ -56,16 +56,19 @@ class CacheValidityPolicy {
|
|||
|
||||
public long getFreshnessLifetimeSecs(final HttpCacheEntry entry) {
|
||||
long maxage = getMaxAge(entry);
|
||||
if (maxage > -1)
|
||||
return maxage;
|
||||
if (maxage > -1) {
|
||||
return maxage;
|
||||
}
|
||||
|
||||
Date dateValue = getDateValue(entry);
|
||||
if (dateValue == null)
|
||||
return 0L;
|
||||
if (dateValue == null) {
|
||||
return 0L;
|
||||
}
|
||||
|
||||
Date expiry = getExpirationDate(entry);
|
||||
if (expiry == null)
|
||||
return 0;
|
||||
if (expiry == null) {
|
||||
return 0;
|
||||
}
|
||||
long diff = expiry.getTime() - dateValue.getTime();
|
||||
return (diff / 1000);
|
||||
}
|
||||
|
@ -99,8 +102,9 @@ class CacheValidityPolicy {
|
|||
|
||||
if (dateValue != null && lastModifiedValue != null) {
|
||||
long diff = dateValue.getTime() - lastModifiedValue.getTime();
|
||||
if (diff < 0)
|
||||
return 0;
|
||||
if (diff < 0) {
|
||||
return 0;
|
||||
}
|
||||
return (long)(coefficient * (diff / 1000));
|
||||
}
|
||||
|
||||
|
@ -170,8 +174,9 @@ class CacheValidityPolicy {
|
|||
|
||||
protected Date getDateValue(final HttpCacheEntry entry) {
|
||||
Header dateHdr = entry.getFirstHeader(HTTP.DATE_HEADER);
|
||||
if (dateHdr == null)
|
||||
return null;
|
||||
if (dateHdr == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return DateUtils.parseDate(dateHdr.getValue());
|
||||
} catch (DateParseException dpe) {
|
||||
|
@ -182,8 +187,9 @@ class CacheValidityPolicy {
|
|||
|
||||
protected Date getLastModifiedValue(final HttpCacheEntry entry) {
|
||||
Header dateHdr = entry.getFirstHeader(HeaderConstants.LAST_MODIFIED);
|
||||
if (dateHdr == null)
|
||||
return null;
|
||||
if (dateHdr == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return DateUtils.parseDate(dateHdr.getValue());
|
||||
} catch (DateParseException dpe) {
|
||||
|
@ -194,8 +200,9 @@ class CacheValidityPolicy {
|
|||
|
||||
protected long getContentLengthValue(final HttpCacheEntry entry) {
|
||||
Header cl = entry.getFirstHeader(HTTP.CONTENT_LEN);
|
||||
if (cl == null)
|
||||
return -1;
|
||||
if (cl == null) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
try {
|
||||
return Long.parseLong(cl.getValue());
|
||||
|
@ -221,11 +228,13 @@ class CacheValidityPolicy {
|
|||
|
||||
protected long getApparentAgeSecs(final HttpCacheEntry entry) {
|
||||
Date dateValue = getDateValue(entry);
|
||||
if (dateValue == null)
|
||||
return MAX_AGE;
|
||||
if (dateValue == null) {
|
||||
return MAX_AGE;
|
||||
}
|
||||
long diff = entry.getResponseDate().getTime() - dateValue.getTime();
|
||||
if (diff < 0L)
|
||||
return 0;
|
||||
if (diff < 0L) {
|
||||
return 0;
|
||||
}
|
||||
return (diff / 1000);
|
||||
}
|
||||
|
||||
|
@ -289,8 +298,9 @@ class CacheValidityPolicy {
|
|||
|
||||
protected Date getExpirationDate(final HttpCacheEntry entry) {
|
||||
Header expiresHeader = entry.getFirstHeader(HeaderConstants.EXPIRES);
|
||||
if (expiresHeader == null)
|
||||
return null;
|
||||
if (expiresHeader == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return DateUtils.parseDate(expiresHeader.getValue());
|
||||
} catch (DateParseException dpe) {
|
||||
|
@ -314,7 +324,9 @@ class CacheValidityPolicy {
|
|||
public long getStalenessSecs(HttpCacheEntry entry, Date now) {
|
||||
long age = getCurrentAgeSecs(entry, now);
|
||||
long freshness = getFreshnessLifetimeSecs(entry);
|
||||
if (age <= freshness) return 0L;
|
||||
if (age <= freshness) {
|
||||
return 0L;
|
||||
}
|
||||
return (age - freshness);
|
||||
}
|
||||
|
||||
|
|
|
@ -151,8 +151,9 @@ class CachedHttpResponseGenerator {
|
|||
}
|
||||
|
||||
private void addMissingContentLengthHeader(HttpResponse response, HttpEntity entity) {
|
||||
if (transferEncodingIsPresent(response))
|
||||
return;
|
||||
if (transferEncodingIsPresent(response)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Header contentLength = response.getFirstHeader(HTTP.CONTENT_LEN);
|
||||
if (contentLength == null) {
|
||||
|
|
|
@ -73,19 +73,30 @@ class CachedResponseSuitabilityChecker {
|
|||
}
|
||||
|
||||
private boolean isFreshEnough(HttpCacheEntry entry, HttpRequest request, Date now) {
|
||||
if (validityStrategy.isResponseFresh(entry, now)) return true;
|
||||
if (validityStrategy.isResponseFresh(entry, now)) {
|
||||
return true;
|
||||
}
|
||||
if (useHeuristicCaching &&
|
||||
validityStrategy.isResponseHeuristicallyFresh(entry, now, heuristicCoefficient, heuristicDefaultLifetime))
|
||||
return true;
|
||||
if (originInsistsOnFreshness(entry)) return false;
|
||||
validityStrategy.isResponseHeuristicallyFresh(entry, now, heuristicCoefficient, heuristicDefaultLifetime)) {
|
||||
return true;
|
||||
}
|
||||
if (originInsistsOnFreshness(entry)) {
|
||||
return false;
|
||||
}
|
||||
long maxstale = getMaxStale(request);
|
||||
if (maxstale == -1) return false;
|
||||
if (maxstale == -1) {
|
||||
return false;
|
||||
}
|
||||
return (maxstale > validityStrategy.getStalenessSecs(entry, now));
|
||||
}
|
||||
|
||||
private boolean originInsistsOnFreshness(HttpCacheEntry entry) {
|
||||
if (validityStrategy.mustRevalidate(entry)) return true;
|
||||
if (!sharedCache) return false;
|
||||
if (validityStrategy.mustRevalidate(entry)) {
|
||||
return true;
|
||||
}
|
||||
if (!sharedCache) {
|
||||
return false;
|
||||
}
|
||||
return validityStrategy.proxyRevalidate(entry) ||
|
||||
validityStrategy.hasCacheControlDirective(entry, "s-maxage");
|
||||
}
|
||||
|
@ -101,7 +112,9 @@ class CachedResponseSuitabilityChecker {
|
|||
} else {
|
||||
try {
|
||||
long val = Long.parseLong(elt.getValue());
|
||||
if (val < 0) val = 0;
|
||||
if (val < 0) {
|
||||
val = 0;
|
||||
}
|
||||
if (maxstale == -1 || val < maxstale) {
|
||||
maxstale = val;
|
||||
}
|
||||
|
@ -198,7 +211,9 @@ class CachedResponseSuitabilityChecker {
|
|||
if (HeaderConstants.CACHE_CONTROL_MIN_FRESH.equals(elt.getName())) {
|
||||
try {
|
||||
long minfresh = Long.parseLong(elt.getValue());
|
||||
if (minfresh < 0L) return false;
|
||||
if (minfresh < 0L) {
|
||||
return false;
|
||||
}
|
||||
long age = validityStrategy.getCurrentAgeSecs(entry, now);
|
||||
long freshness = validityStrategy.getFreshnessLifetimeSecs(entry);
|
||||
if (freshness - age < minfresh) {
|
||||
|
|
|
@ -486,7 +486,9 @@ public class CachingExec implements ClientExecChain {
|
|||
int maxstale = Integer.parseInt(elt.getValue());
|
||||
long age = validityPolicy.getCurrentAgeSecs(entry, now);
|
||||
long lifetime = validityPolicy.getFreshnessLifetimeSecs(entry);
|
||||
if (age - lifetime > maxstale) return true;
|
||||
if (age - lifetime > maxstale) {
|
||||
return true;
|
||||
}
|
||||
} catch (NumberFormatException nfe) {
|
||||
return true;
|
||||
}
|
||||
|
@ -503,7 +505,9 @@ public class CachingExec implements ClientExecChain {
|
|||
|
||||
final ProtocolVersion pv = msg.getProtocolVersion();
|
||||
String existingEntry = viaHeaders.get(pv);
|
||||
if (existingEntry != null) return existingEntry;
|
||||
if (existingEntry != null) {
|
||||
return existingEntry;
|
||||
}
|
||||
|
||||
final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.http.client", getClass().getClassLoader());
|
||||
final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
|
||||
|
@ -544,14 +548,17 @@ public class CachingExec implements ClientExecChain {
|
|||
boolean clientRequestsOurOptions(final HttpRequest request) {
|
||||
RequestLine line = request.getRequestLine();
|
||||
|
||||
if (!HeaderConstants.OPTIONS_METHOD.equals(line.getMethod()))
|
||||
return false;
|
||||
if (!HeaderConstants.OPTIONS_METHOD.equals(line.getMethod())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!"*".equals(line.getUri()))
|
||||
return false;
|
||||
if (!"*".equals(line.getUri())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!"0".equals(request.getFirstHeader(HeaderConstants.MAX_FORWARDS).getValue()))
|
||||
return false;
|
||||
if (!"0".equals(request.getFirstHeader(HeaderConstants.MAX_FORWARDS).getValue())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
@ -587,7 +594,9 @@ public class CachingExec implements ClientExecChain {
|
|||
try {
|
||||
Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
|
||||
Date respDate = DateUtils.parseDate(responseDateHeader.getValue());
|
||||
if (respDate.before(entryDate)) return true;
|
||||
if (respDate.before(entryDate)) {
|
||||
return true;
|
||||
}
|
||||
} catch (DateParseException e) {
|
||||
// either backend response or cached entry did not have a valid
|
||||
// Date header, so we can't tell if they are out of order
|
||||
|
@ -843,11 +852,17 @@ public class CachingExec implements ClientExecChain {
|
|||
} catch (IOException ioe) {
|
||||
// nop
|
||||
}
|
||||
if (existing == null) return false;
|
||||
if (existing == null) {
|
||||
return false;
|
||||
}
|
||||
Header entryDateHeader = existing.getFirstHeader(HTTP.DATE_HEADER);
|
||||
if (entryDateHeader == null) return false;
|
||||
if (entryDateHeader == null) {
|
||||
return false;
|
||||
}
|
||||
Header responseDateHeader = backendResponse.getFirstHeader(HTTP.DATE_HEADER);
|
||||
if (responseDateHeader == null) return false;
|
||||
if (responseDateHeader == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
|
||||
Date responseDate = DateUtils.parseDate(responseDateHeader.getValue());
|
||||
|
|
|
@ -432,7 +432,9 @@ public class CachingHttpClient implements HttpClient {
|
|||
|
||||
HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse(
|
||||
request, context);
|
||||
if (fatalErrorResponse != null) return fatalErrorResponse;
|
||||
if (fatalErrorResponse != null) {
|
||||
return fatalErrorResponse;
|
||||
}
|
||||
|
||||
requestCompliance.makeRequestCompliant(request);
|
||||
request.addHeader("Via",via);
|
||||
|
@ -651,7 +653,9 @@ public class CachingHttpClient implements HttpClient {
|
|||
int maxstale = Integer.parseInt(elt.getValue());
|
||||
long age = validityPolicy.getCurrentAgeSecs(entry, now);
|
||||
long lifetime = validityPolicy.getFreshnessLifetimeSecs(entry);
|
||||
if (age - lifetime > maxstale) return true;
|
||||
if (age - lifetime > maxstale) {
|
||||
return true;
|
||||
}
|
||||
} catch (NumberFormatException nfe) {
|
||||
return true;
|
||||
}
|
||||
|
@ -668,7 +672,9 @@ public class CachingHttpClient implements HttpClient {
|
|||
|
||||
final ProtocolVersion pv = msg.getProtocolVersion();
|
||||
String existingEntry = viaHeaders.get(pv);
|
||||
if (existingEntry != null) return existingEntry;
|
||||
if (existingEntry != null) {
|
||||
return existingEntry;
|
||||
}
|
||||
|
||||
final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.http.client", getClass().getClassLoader());
|
||||
final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
|
||||
|
@ -720,14 +726,17 @@ public class CachingHttpClient implements HttpClient {
|
|||
boolean clientRequestsOurOptions(HttpRequest request) {
|
||||
RequestLine line = request.getRequestLine();
|
||||
|
||||
if (!HeaderConstants.OPTIONS_METHOD.equals(line.getMethod()))
|
||||
return false;
|
||||
if (!HeaderConstants.OPTIONS_METHOD.equals(line.getMethod())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!"*".equals(line.getUri()))
|
||||
return false;
|
||||
if (!"*".equals(line.getUri())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!"0".equals(request.getFirstHeader(HeaderConstants.MAX_FORWARDS).getValue()))
|
||||
return false;
|
||||
if (!"0".equals(request.getFirstHeader(HeaderConstants.MAX_FORWARDS).getValue())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
@ -753,7 +762,9 @@ public class CachingHttpClient implements HttpClient {
|
|||
try {
|
||||
Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
|
||||
Date respDate = DateUtils.parseDate(responseDateHeader.getValue());
|
||||
if (respDate.before(entryDate)) return true;
|
||||
if (respDate.before(entryDate)) {
|
||||
return true;
|
||||
}
|
||||
} catch (DateParseException e) {
|
||||
// either backend response or cached entry did not have a valid
|
||||
// Date header, so we can't tell if they are out of order
|
||||
|
@ -898,7 +909,9 @@ public class CachingHttpClient implements HttpClient {
|
|||
final HttpResponse cachedResponse = responseGenerator.generateResponse(cacheEntry);
|
||||
cachedResponse.addHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\"");
|
||||
HttpEntity errorBody = backendResponse.getEntity();
|
||||
if (errorBody != null) EntityUtils.consume(errorBody);
|
||||
if (errorBody != null) {
|
||||
EntityUtils.consume(errorBody);
|
||||
}
|
||||
return cachedResponse;
|
||||
}
|
||||
|
||||
|
@ -971,11 +984,17 @@ public class CachingHttpClient implements HttpClient {
|
|||
} catch (IOException ioe) {
|
||||
// nop
|
||||
}
|
||||
if (existing == null) return false;
|
||||
if (existing == null) {
|
||||
return false;
|
||||
}
|
||||
Header entryDateHeader = existing.getFirstHeader(HTTP.DATE_HEADER);
|
||||
if (entryDateHeader == null) return false;
|
||||
if (entryDateHeader == null) {
|
||||
return false;
|
||||
}
|
||||
Header responseDateHeader = backendResponse.getFirstHeader(HTTP.DATE_HEADER);
|
||||
if (responseDateHeader == null) return false;
|
||||
if (responseDateHeader == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
|
||||
Date responseDate = DateUtils.parseDate(responseDateHeader.getValue());
|
||||
|
|
|
@ -125,7 +125,9 @@ class RequestProtocolCompliance {
|
|||
}
|
||||
}
|
||||
}
|
||||
if (!shouldStrip) return;
|
||||
if (!shouldStrip) {
|
||||
return;
|
||||
}
|
||||
request.removeHeaders(HeaderConstants.CACHE_CONTROL);
|
||||
request.setHeader(HeaderConstants.CACHE_CONTROL, buildHeaderFromElements(outElts));
|
||||
}
|
||||
|
@ -301,12 +303,14 @@ class RequestProtocolCompliance {
|
|||
}
|
||||
|
||||
Header range = request.getFirstHeader(HeaderConstants.RANGE);
|
||||
if (range == null)
|
||||
return null;
|
||||
if (range == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Header ifRange = request.getFirstHeader(HeaderConstants.IF_RANGE);
|
||||
if (ifRange == null)
|
||||
return null;
|
||||
if (ifRange == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String val = ifRange.getValue();
|
||||
if (val.startsWith("W/")) {
|
||||
|
@ -333,8 +337,9 @@ class RequestProtocolCompliance {
|
|||
}
|
||||
} else {
|
||||
Header ifNoneMatch = request.getFirstHeader(HeaderConstants.IF_NONE_MATCH);
|
||||
if (ifNoneMatch == null)
|
||||
return null;
|
||||
if (ifNoneMatch == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String val2 = ifNoneMatch.getValue();
|
||||
if (val2.startsWith("W/")) {
|
||||
|
|
|
@ -115,24 +115,28 @@ class ResponseCachingPolicy {
|
|||
Header contentLength = response.getFirstHeader(HTTP.CONTENT_LEN);
|
||||
if (contentLength != null) {
|
||||
int contentLengthValue = Integer.parseInt(contentLength.getValue());
|
||||
if (contentLengthValue > this.maxObjectSizeBytes)
|
||||
return false;
|
||||
if (contentLengthValue > this.maxObjectSizeBytes) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Header[] ageHeaders = response.getHeaders(HeaderConstants.AGE);
|
||||
|
||||
if (ageHeaders.length > 1)
|
||||
return false;
|
||||
if (ageHeaders.length > 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Header[] expiresHeaders = response.getHeaders(HeaderConstants.EXPIRES);
|
||||
|
||||
if (expiresHeaders.length > 1)
|
||||
return false;
|
||||
if (expiresHeaders.length > 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Header[] dateHeaders = response.getHeaders(HTTP.DATE_HEADER);
|
||||
|
||||
if (dateHeaders.length != 1)
|
||||
return false;
|
||||
if (dateHeaders.length != 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
DateUtils.parseDate(dateHeaders[0].getValue());
|
||||
|
@ -148,18 +152,29 @@ class ResponseCachingPolicy {
|
|||
}
|
||||
}
|
||||
|
||||
if (isExplicitlyNonCacheable(response))
|
||||
return false;
|
||||
if (isExplicitlyNonCacheable(response)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (cacheable || isExplicitlyCacheable(response));
|
||||
}
|
||||
|
||||
private boolean unknownStatusCode(int status) {
|
||||
if (status >= 100 && status <= 101) return false;
|
||||
if (status >= 200 && status <= 206) return false;
|
||||
if (status >= 300 && status <= 307) return false;
|
||||
if (status >= 400 && status <= 417) return false;
|
||||
if (status >= 500 && status <= 505) return false;
|
||||
if (status >= 100 && status <= 101) {
|
||||
return false;
|
||||
}
|
||||
if (status >= 200 && status <= 206) {
|
||||
return false;
|
||||
}
|
||||
if (status >= 300 && status <= 307) {
|
||||
return false;
|
||||
}
|
||||
if (status >= 400 && status <= 417) {
|
||||
return false;
|
||||
}
|
||||
if (status >= 500 && status <= 505) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
@ -192,8 +207,9 @@ class ResponseCachingPolicy {
|
|||
}
|
||||
|
||||
protected boolean isExplicitlyCacheable(HttpResponse response) {
|
||||
if (response.getFirstHeader(HeaderConstants.EXPIRES) != null)
|
||||
return true;
|
||||
if (response.getFirstHeader(HeaderConstants.EXPIRES) != null) {
|
||||
return true;
|
||||
}
|
||||
String[] cacheableParams = { HeaderConstants.CACHE_CONTROL_MAX_AGE, "s-maxage",
|
||||
HeaderConstants.CACHE_CONTROL_MUST_REVALIDATE,
|
||||
HeaderConstants.CACHE_CONTROL_PROXY_REVALIDATE,
|
||||
|
@ -251,10 +267,14 @@ class ResponseCachingPolicy {
|
|||
|
||||
private boolean expiresHeaderLessOrEqualToDateHeaderAndNoCacheControl(
|
||||
HttpResponse response) {
|
||||
if (response.getFirstHeader(HeaderConstants.CACHE_CONTROL) != null) return false;
|
||||
if (response.getFirstHeader(HeaderConstants.CACHE_CONTROL) != null) {
|
||||
return false;
|
||||
}
|
||||
Header expiresHdr = response.getFirstHeader(HeaderConstants.EXPIRES);
|
||||
Header dateHdr = response.getFirstHeader(HTTP.DATE_HEADER);
|
||||
if (expiresHdr == null || dateHdr == null) return false;
|
||||
if (expiresHdr == null || dateHdr == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Date expires = DateUtils.parseDate(expiresHdr.getValue());
|
||||
Date date = DateUtils.parseDate(dateHdr.getValue());
|
||||
|
|
|
@ -94,7 +94,9 @@ class ResponseProtocolCompliance {
|
|||
|
||||
private void consumeBody(HttpResponse response) throws IOException {
|
||||
HttpEntity body = response.getEntity();
|
||||
if (body != null) EntityUtils.consume(body);
|
||||
if (body != null) {
|
||||
EntityUtils.consume(body);
|
||||
}
|
||||
}
|
||||
|
||||
private void warningsWithNonMatchingWarnDatesAreRemoved(
|
||||
|
@ -106,11 +108,15 @@ class ResponseProtocolCompliance {
|
|||
//Empty On Purpose
|
||||
}
|
||||
|
||||
if (responseDate == null) return;
|
||||
if (responseDate == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Header[] warningHeaders = response.getHeaders(HeaderConstants.WARNING);
|
||||
|
||||
if (warningHeaders == null || warningHeaders.length == 0) return;
|
||||
if (warningHeaders == null || warningHeaders.length == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<Header> newWarningHeaders = new ArrayList<Header>();
|
||||
boolean modified = false;
|
||||
|
@ -134,7 +140,9 @@ class ResponseProtocolCompliance {
|
|||
|
||||
private void identityIsNotUsedInContentEncoding(HttpResponse response) {
|
||||
Header[] hdrs = response.getHeaders(HTTP.CONTENT_ENCODING);
|
||||
if (hdrs == null || hdrs.length == 0) return;
|
||||
if (hdrs == null || hdrs.length == 0) {
|
||||
return;
|
||||
}
|
||||
List<Header> newHeaders = new ArrayList<Header>();
|
||||
boolean modified = false;
|
||||
for (Header h : hdrs) {
|
||||
|
@ -144,7 +152,9 @@ class ResponseProtocolCompliance {
|
|||
if ("identity".equalsIgnoreCase(elt.getName())) {
|
||||
modified = true;
|
||||
} else {
|
||||
if (!first) buf.append(",");
|
||||
if (!first) {
|
||||
buf.append(",");
|
||||
}
|
||||
buf.append(elt.toString());
|
||||
first = false;
|
||||
}
|
||||
|
@ -154,7 +164,9 @@ class ResponseProtocolCompliance {
|
|||
newHeaders.add(new BasicHeader(HTTP.CONTENT_ENCODING, newHeaderValue));
|
||||
}
|
||||
}
|
||||
if (!modified) return;
|
||||
if (!modified) {
|
||||
return;
|
||||
}
|
||||
response.removeHeaders(HTTP.CONTENT_ENCODING);
|
||||
for (Header h : newHeaders) {
|
||||
response.addHeader(h);
|
||||
|
@ -171,8 +183,9 @@ class ResponseProtocolCompliance {
|
|||
private void ensurePartialContentIsNotSentToAClientThatDidNotRequestIt(HttpRequest request,
|
||||
HttpResponse response) throws IOException {
|
||||
if (request.getFirstHeader(HeaderConstants.RANGE) != null
|
||||
|| response.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT)
|
||||
return;
|
||||
|| response.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT) {
|
||||
return;
|
||||
}
|
||||
|
||||
consumeBody(response);
|
||||
throw new ClientProtocolException(UNEXPECTED_PARTIAL_CONTENT);
|
||||
|
@ -220,7 +233,9 @@ class ResponseProtocolCompliance {
|
|||
|
||||
HttpRequest originalRequest = request.getOriginal();
|
||||
if (originalRequest instanceof HttpEntityEnclosingRequest) {
|
||||
if (((HttpEntityEnclosingRequest)originalRequest).expectContinue()) return;
|
||||
if (((HttpEntityEnclosingRequest)originalRequest).expectContinue()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
consumeBody(response);
|
||||
throw new ClientProtocolException(UNEXPECTED_100_CONTINUE);
|
||||
|
|
|
@ -80,7 +80,9 @@ class WarningValue {
|
|||
offs = wv.offs;
|
||||
} catch (IllegalArgumentException e) {
|
||||
final int nextComma = src.indexOf(',', offs);
|
||||
if (nextComma == -1) break;
|
||||
if (nextComma == -1) {
|
||||
break;
|
||||
}
|
||||
offs = nextComma + 1;
|
||||
}
|
||||
}
|
||||
|
@ -149,9 +151,13 @@ class WarningValue {
|
|||
* token = 1*<any CHAR except CTLs or separators>
|
||||
*/
|
||||
protected void consumeToken() {
|
||||
if (!isTokenChar(src.charAt(offs))) parseError();
|
||||
if (!isTokenChar(src.charAt(offs))) {
|
||||
parseError();
|
||||
}
|
||||
while(offs < src.length()) {
|
||||
if (!isTokenChar(src.charAt(offs))) break;
|
||||
if (!isTokenChar(src.charAt(offs))) {
|
||||
break;
|
||||
}
|
||||
offs++;
|
||||
}
|
||||
}
|
||||
|
@ -171,8 +177,12 @@ class WarningValue {
|
|||
|
||||
protected void consumeHostPort() {
|
||||
Matcher m = HOSTPORT_PATTERN.matcher(src.substring(offs));
|
||||
if (!m.find()) parseError();
|
||||
if (m.start() != 0) parseError();
|
||||
if (!m.find()) {
|
||||
parseError();
|
||||
}
|
||||
if (m.start() != 0) {
|
||||
parseError();
|
||||
}
|
||||
offs += m.end();
|
||||
}
|
||||
|
||||
|
@ -201,7 +211,9 @@ class WarningValue {
|
|||
* qdtext = <any TEXT except <">>
|
||||
*/
|
||||
protected void consumeQuotedString() {
|
||||
if (src.charAt(offs) != '\"') parseError();
|
||||
if (src.charAt(offs) != '\"') {
|
||||
parseError();
|
||||
}
|
||||
offs++;
|
||||
boolean foundEnd = false;
|
||||
while(offs < src.length() && !foundEnd) {
|
||||
|
@ -218,7 +230,9 @@ class WarningValue {
|
|||
parseError();
|
||||
}
|
||||
}
|
||||
if (!foundEnd) parseError();
|
||||
if (!foundEnd) {
|
||||
parseError();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
|
@ -250,7 +264,9 @@ class WarningValue {
|
|||
protected void consumeWarnDate() {
|
||||
int curr = offs;
|
||||
Matcher m = WARN_DATE_PATTERN.matcher(src.substring(offs));
|
||||
if (!m.lookingAt()) parseError();
|
||||
if (!m.lookingAt()) {
|
||||
parseError();
|
||||
}
|
||||
offs += m.end();
|
||||
try {
|
||||
warnDate = DateUtils.parseDate(src.substring(curr+1,offs-1));
|
||||
|
|
|
@ -161,7 +161,9 @@ public class MemcachedHttpCacheStorage implements HttpCacheStorage {
|
|||
public void putEntry(String url, HttpCacheEntry entry) throws IOException {
|
||||
byte[] bytes = serializeEntry(url, entry);
|
||||
String key = getCacheKey(url);
|
||||
if (key == null) return;
|
||||
if (key == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
client.set(key, 0, bytes);
|
||||
} catch (OperationTimeoutException ex) {
|
||||
|
@ -189,7 +191,9 @@ public class MemcachedHttpCacheStorage implements HttpCacheStorage {
|
|||
}
|
||||
|
||||
private byte[] convertToByteArray(Object o) {
|
||||
if (o == null) return null;
|
||||
if (o == null) {
|
||||
return null;
|
||||
}
|
||||
if (!(o instanceof byte[])) {
|
||||
log.warn("got a non-bytearray back from memcached: " + o);
|
||||
return null;
|
||||
|
@ -199,7 +203,9 @@ public class MemcachedHttpCacheStorage implements HttpCacheStorage {
|
|||
|
||||
private MemcachedCacheEntry reconstituteEntry(Object o) throws IOException {
|
||||
byte[] bytes = convertToByteArray(o);
|
||||
if (bytes == null) return null;
|
||||
if (bytes == null) {
|
||||
return null;
|
||||
}
|
||||
MemcachedCacheEntry mce = memcachedCacheEntryFactory.getUnsetCacheEntry();
|
||||
try {
|
||||
mce.set(bytes);
|
||||
|
@ -211,10 +217,14 @@ public class MemcachedHttpCacheStorage implements HttpCacheStorage {
|
|||
|
||||
public HttpCacheEntry getEntry(String url) throws IOException {
|
||||
String key = getCacheKey(url);
|
||||
if (key == null) return null;
|
||||
if (key == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
MemcachedCacheEntry mce = reconstituteEntry(client.get(key));
|
||||
if (mce == null || !url.equals(mce.getStorageKey())) return null;
|
||||
if (mce == null || !url.equals(mce.getStorageKey())) {
|
||||
return null;
|
||||
}
|
||||
return mce.getHttpCacheEntry();
|
||||
} catch (OperationTimeoutException ex) {
|
||||
throw new MemcachedOperationTimeoutException(ex);
|
||||
|
@ -223,7 +233,9 @@ public class MemcachedHttpCacheStorage implements HttpCacheStorage {
|
|||
|
||||
public void removeEntry(String url) throws IOException {
|
||||
String key = getCacheKey(url);
|
||||
if (key == null) return;
|
||||
if (key == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
client.delete(key);
|
||||
} catch (OperationTimeoutException ex) {
|
||||
|
@ -260,7 +272,9 @@ public class MemcachedHttpCacheStorage implements HttpCacheStorage {
|
|||
updatedBytes);
|
||||
if (casResult != CASResponse.OK) {
|
||||
numRetries++;
|
||||
} else return;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch (OperationTimeoutException ex) {
|
||||
throw new MemcachedOperationTimeoutException(ex);
|
||||
|
|
|
@ -96,8 +96,9 @@ public class HttpTestUtils {
|
|||
*/
|
||||
public static boolean isHopByHopHeader(String name) {
|
||||
for (String s : HOP_BY_HOP_HEADERS) {
|
||||
if (s.equalsIgnoreCase(name))
|
||||
return true;
|
||||
if (s.equalsIgnoreCase(name)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
@ -107,8 +108,9 @@ public class HttpTestUtils {
|
|||
*/
|
||||
public static boolean isMultiHeader(String name) {
|
||||
for (String s : MULTI_HEADERS) {
|
||||
if (s.equalsIgnoreCase(name))
|
||||
return true;
|
||||
if (s.equalsIgnoreCase(name)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
@ -118,8 +120,9 @@ public class HttpTestUtils {
|
|||
*/
|
||||
public static boolean isSingleHeader(String name) {
|
||||
for (String s : SINGLE_HEADERS) {
|
||||
if (s.equalsIgnoreCase(name))
|
||||
return true;
|
||||
if (s.equalsIgnoreCase(name)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
@ -129,14 +132,18 @@ public class HttpTestUtils {
|
|||
public static boolean equivalent(HttpEntity e1, HttpEntity e2) throws Exception {
|
||||
InputStream i1 = e1.getContent();
|
||||
InputStream i2 = e2.getContent();
|
||||
if (i1 == null && i2 == null)
|
||||
return true;
|
||||
if (i1 == null && i2 == null) {
|
||||
return true;
|
||||
}
|
||||
if (i1 == null || i2 == null)
|
||||
return false; // avoid possible NPEs below
|
||||
{
|
||||
return false; // avoid possible NPEs below
|
||||
}
|
||||
int b1 = -1;
|
||||
while ((b1 = i1.read()) != -1) {
|
||||
if (b1 != i2.read())
|
||||
return false;
|
||||
if (b1 != i2.read()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return (-1 == i2.read());
|
||||
}
|
||||
|
@ -199,8 +206,9 @@ public class HttpTestUtils {
|
|||
if (!isHopByHopHeader(h.getName())) {
|
||||
String r1val = getCanonicalHeaderValue(r1, h.getName());
|
||||
String r2val = getCanonicalHeaderValue(r2, h.getName());
|
||||
if (!r1val.equals(r2val))
|
||||
return false;
|
||||
if (!r1val.equals(r2val)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
|
@ -218,9 +226,13 @@ public class HttpTestUtils {
|
|||
public static boolean semanticallyTransparent(HttpResponse r1, HttpResponse r2)
|
||||
throws Exception {
|
||||
final boolean entitiesEquivalent = equivalent(r1.getEntity(), r2.getEntity());
|
||||
if (!entitiesEquivalent) return false;
|
||||
if (!entitiesEquivalent) {
|
||||
return false;
|
||||
}
|
||||
final boolean statusLinesEquivalent = semanticallyTransparent(r1.getStatusLine(), r2.getStatusLine());
|
||||
if (!statusLinesEquivalent) return false;
|
||||
if (!statusLinesEquivalent) {
|
||||
return false;
|
||||
}
|
||||
final boolean e2eHeadersEquivalentSubset = isEndToEndHeaderSubset(
|
||||
r1, r2);
|
||||
return e2eHeadersEquivalentSubset;
|
||||
|
|
|
@ -38,8 +38,9 @@ public class RequestEquivalent implements IArgumentMatcher {
|
|||
}
|
||||
|
||||
public boolean matches(Object actual) {
|
||||
if (!(actual instanceof HttpRequest))
|
||||
return false;
|
||||
if (!(actual instanceof HttpRequest)) {
|
||||
return false;
|
||||
}
|
||||
HttpRequest other = (HttpRequest) actual;
|
||||
return HttpTestUtils.equivalent(expected, other);
|
||||
}
|
||||
|
|
|
@ -1413,8 +1413,9 @@ public class TestCachingExec {
|
|||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
if (closed)
|
||||
throw new SocketException("Socket closed");
|
||||
if (closed) {
|
||||
throw new SocketException("Socket closed");
|
||||
}
|
||||
throw new SocketTimeoutException("Read timed out");
|
||||
}
|
||||
}, 128));
|
||||
|
|
|
@ -102,29 +102,36 @@ public class TestHttpCacheEntrySerializers {
|
|||
private boolean areEqual(HttpCacheEntry one, HttpCacheEntry two) throws IOException {
|
||||
// dates are only stored with second precision, so scrub milliseconds
|
||||
if (!((one.getRequestDate().getTime() / 1000) == (two.getRequestDate()
|
||||
.getTime() / 1000)))
|
||||
return false;
|
||||
.getTime() / 1000))) {
|
||||
return false;
|
||||
}
|
||||
if (!((one.getResponseDate().getTime() / 1000) == (two
|
||||
.getResponseDate().getTime() / 1000)))
|
||||
return false;
|
||||
if (!one.getProtocolVersion().equals(two.getProtocolVersion()))
|
||||
return false;
|
||||
.getResponseDate().getTime() / 1000))) {
|
||||
return false;
|
||||
}
|
||||
if (!one.getProtocolVersion().equals(two.getProtocolVersion())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
byte[] onesByteArray = resourceToBytes(one.getResource());
|
||||
byte[] twosByteArray = resourceToBytes(two.getResource());
|
||||
|
||||
if (!Arrays.equals(onesByteArray,twosByteArray))
|
||||
return false;
|
||||
if (!Arrays.equals(onesByteArray,twosByteArray)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Header[] oneHeaders = one.getAllHeaders();
|
||||
Header[] twoHeaders = two.getAllHeaders();
|
||||
if (!(oneHeaders.length == twoHeaders.length))
|
||||
return false;
|
||||
if (!(oneHeaders.length == twoHeaders.length)) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < oneHeaders.length; i++) {
|
||||
if (!oneHeaders[i].getName().equals(twoHeaders[i].getName()))
|
||||
return false;
|
||||
if (!oneHeaders[i].getValue().equals(twoHeaders[i].getValue()))
|
||||
return false;
|
||||
if (!oneHeaders[i].getName().equals(twoHeaders[i].getName())) {
|
||||
return false;
|
||||
}
|
||||
if (!oneHeaders[i].getValue().equals(twoHeaders[i].getValue())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
|
|
|
@ -1651,10 +1651,12 @@ public class TestProtocolRequirements extends AbstractProtocolTest {
|
|||
boolean found1 = false;
|
||||
boolean found2 = false;
|
||||
while ((b = i.read()) != -1) {
|
||||
if (b == 1)
|
||||
found1 = true;
|
||||
if (b == 2)
|
||||
found2 = true;
|
||||
if (b == 1) {
|
||||
found1 = true;
|
||||
}
|
||||
if (b == 2) {
|
||||
found2 = true;
|
||||
}
|
||||
}
|
||||
i.close();
|
||||
Assert.assertFalse(found1 && found2); // mixture of content
|
||||
|
@ -1743,10 +1745,12 @@ public class TestProtocolRequirements extends AbstractProtocolTest {
|
|||
boolean found1 = false;
|
||||
boolean found2 = false;
|
||||
while ((b = i.read()) != -1) {
|
||||
if (b == 1)
|
||||
found1 = true;
|
||||
if (b == 2)
|
||||
found2 = true;
|
||||
if (b == 1) {
|
||||
found1 = true;
|
||||
}
|
||||
if (b == 2) {
|
||||
found2 = true;
|
||||
}
|
||||
}
|
||||
i.close();
|
||||
Assert.assertFalse(found1 && found2); // mixture of content
|
||||
|
@ -2609,8 +2613,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest {
|
|||
if (status == 200) {
|
||||
boolean foundWarning = false;
|
||||
for (Header h : result.getHeaders("Warning")) {
|
||||
if (h.getValue().split(" ")[0].equals("111"))
|
||||
foundWarning = true;
|
||||
if (h.getValue().split(" ")[0].equals("111")) {
|
||||
foundWarning = true;
|
||||
}
|
||||
}
|
||||
Assert.assertTrue(foundWarning);
|
||||
} else {
|
||||
|
@ -2686,14 +2691,16 @@ public class TestProtocolRequirements extends AbstractProtocolTest {
|
|||
boolean found1xxWarning = false;
|
||||
for (Header h : result1.getHeaders("Warning")) {
|
||||
for (HeaderElement elt : h.getElements()) {
|
||||
if (elt.getName().startsWith("1"))
|
||||
found1xxWarning = true;
|
||||
if (elt.getName().startsWith("1")) {
|
||||
found1xxWarning = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Header h : result2.getHeaders("Warning")) {
|
||||
for (HeaderElement elt : h.getElements()) {
|
||||
if (elt.getName().startsWith("1"))
|
||||
found1xxWarning = true;
|
||||
if (elt.getName().startsWith("1")) {
|
||||
found1xxWarning = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Assert.assertFalse(found1xxWarning);
|
||||
|
@ -2757,8 +2764,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest {
|
|||
for (Header h : result1.getHeaders("Warning")) {
|
||||
for (HeaderElement elt : h.getElements()) {
|
||||
String[] parts = elt.getName().split(" ");
|
||||
if ("214".equals(parts[0]))
|
||||
found214Warning = true;
|
||||
if ("214".equals(parts[0])) {
|
||||
found214Warning = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Assert.assertTrue(found214Warning);
|
||||
|
@ -2767,8 +2775,9 @@ public class TestProtocolRequirements extends AbstractProtocolTest {
|
|||
for (Header h : result2.getHeaders("Warning")) {
|
||||
for (HeaderElement elt : h.getElements()) {
|
||||
String[] parts = elt.getName().split(" ");
|
||||
if ("214".equals(parts[0]))
|
||||
found214Warning = true;
|
||||
if ("214".equals(parts[0])) {
|
||||
found214Warning = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Assert.assertTrue(found214Warning);
|
||||
|
@ -3160,14 +3169,16 @@ public class TestProtocolRequirements extends AbstractProtocolTest {
|
|||
boolean foundETag = false;
|
||||
for (Header h : validation.getHeaders("If-Match")) {
|
||||
for (HeaderElement elt : h.getElements()) {
|
||||
if ("W/\"etag\"".equals(elt.getName()))
|
||||
foundETag = true;
|
||||
if ("W/\"etag\"".equals(elt.getName())) {
|
||||
foundETag = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Header h : validation.getHeaders("If-None-Match")) {
|
||||
for (HeaderElement elt : h.getElements()) {
|
||||
if ("W/\"etag\"".equals(elt.getName()))
|
||||
foundETag = true;
|
||||
if ("W/\"etag\"".equals(elt.getName())) {
|
||||
foundETag = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Assert.assertTrue(foundETag);
|
||||
|
@ -6050,11 +6061,17 @@ public class TestProtocolRequirements extends AbstractProtocolTest {
|
|||
final String nestedPrefix = "^\\(([^\\p{Cntrl}()]|\\\\\\p{ASCII})*\\(";
|
||||
final String nestedSuffix = "\\)([^\\p{Cntrl}()]|\\\\\\p{ASCII})*\\)$";
|
||||
|
||||
if (Pattern.matches(leafComment,s)) return true;
|
||||
if (Pattern.matches(leafComment,s)) {
|
||||
return true;
|
||||
}
|
||||
Matcher pref = Pattern.compile(nestedPrefix).matcher(s);
|
||||
Matcher suff = Pattern.compile(nestedSuffix).matcher(s);
|
||||
if (!pref.find()) return false;
|
||||
if (!suff.find()) return false;
|
||||
if (!pref.find()) {
|
||||
return false;
|
||||
}
|
||||
if (!suff.find()) {
|
||||
return false;
|
||||
}
|
||||
return isValidComment(s.substring(pref.end() - 1, suff.start() + 1));
|
||||
}
|
||||
|
||||
|
|
|
@ -486,7 +486,9 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
|
|||
|
||||
HttpCacheUpdateCallback callback = new HttpCacheUpdateCallback() {
|
||||
public HttpCacheEntry update(HttpCacheEntry old) {
|
||||
if (old == existingValue) return updatedValue;
|
||||
if (old == existingValue) {
|
||||
return updatedValue;
|
||||
}
|
||||
assertSame(existingValue2, old);
|
||||
return updatedValue2;
|
||||
}
|
||||
|
|
|
@ -64,7 +64,9 @@ public final class BasicUserPrincipal implements Principal, Serializable {
|
|||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o instanceof BasicUserPrincipal) {
|
||||
BasicUserPrincipal that = (BasicUserPrincipal) o;
|
||||
if (LangUtils.equals(this.username, that.username)) {
|
||||
|
|
|
@ -150,7 +150,9 @@ public class NTCredentials implements Credentials, Serializable {
|
|||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o instanceof NTCredentials) {
|
||||
NTCredentials that = (NTCredentials) o;
|
||||
if (LangUtils.equals(this.principal, that.principal)
|
||||
|
|
|
@ -92,7 +92,9 @@ public class NTUserPrincipal implements Principal, Serializable {
|
|||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o instanceof NTUserPrincipal) {
|
||||
NTUserPrincipal that = (NTUserPrincipal) o;
|
||||
if (LangUtils.equals(this.username, that.username)
|
||||
|
|
|
@ -99,7 +99,9 @@ public class UsernamePasswordCredentials implements Credentials, Serializable {
|
|||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o instanceof UsernamePasswordCredentials) {
|
||||
UsernamePasswordCredentials that = (UsernamePasswordCredentials) o;
|
||||
if (LangUtils.equals(this.principal, that.principal)) {
|
||||
|
|
|
@ -48,8 +48,11 @@ public class Rfc3492Idn implements Idn {
|
|||
private static final String ACE_PREFIX = "xn--";
|
||||
|
||||
private int adapt(int delta, int numpoints, boolean firsttime) {
|
||||
if (firsttime) delta = delta / damp;
|
||||
else delta = delta / 2;
|
||||
if (firsttime) {
|
||||
delta = delta / damp;
|
||||
} else {
|
||||
delta = delta / 2;
|
||||
}
|
||||
delta = delta + (delta / numpoints);
|
||||
int k = 0;
|
||||
while (delta > ((base - tmin) * tmax) / 2) {
|
||||
|
@ -60,9 +63,15 @@ public class Rfc3492Idn implements Idn {
|
|||
}
|
||||
|
||||
private int digit(char c) {
|
||||
if ((c >= 'A') && (c <= 'Z')) return (c - 'A');
|
||||
if ((c >= 'a') && (c <= 'z')) return (c - 'a');
|
||||
if ((c >= '0') && (c <= '9')) return (c - '0') + 26;
|
||||
if ((c >= 'A') && (c <= 'Z')) {
|
||||
return (c - 'A');
|
||||
}
|
||||
if ((c >= 'a') && (c <= 'z')) {
|
||||
return (c - 'a');
|
||||
}
|
||||
if ((c >= '0') && (c <= '9')) {
|
||||
return (c - '0') + 26;
|
||||
}
|
||||
throw new IllegalArgumentException("illegal digit: "+ c);
|
||||
}
|
||||
|
||||
|
@ -71,8 +80,12 @@ public class Rfc3492Idn implements Idn {
|
|||
StringTokenizer tok = new StringTokenizer(punycode, ".");
|
||||
while (tok.hasMoreTokens()) {
|
||||
String t = tok.nextToken();
|
||||
if (unicode.length() > 0) unicode.append('.');
|
||||
if (t.startsWith(ACE_PREFIX)) t = decode(t.substring(4));
|
||||
if (unicode.length() > 0) {
|
||||
unicode.append('.');
|
||||
}
|
||||
if (t.startsWith(ACE_PREFIX)) {
|
||||
t = decode(t.substring(4));
|
||||
}
|
||||
unicode.append(t);
|
||||
}
|
||||
return unicode.toString();
|
||||
|
@ -93,7 +106,9 @@ public class Rfc3492Idn implements Idn {
|
|||
int oldi = i;
|
||||
int w = 1;
|
||||
for (int k = base;; k += base) {
|
||||
if (input.length() == 0) break;
|
||||
if (input.length() == 0) {
|
||||
break;
|
||||
}
|
||||
char c = input.charAt(0);
|
||||
input = input.substring(1);
|
||||
int digit = digit(c);
|
||||
|
@ -106,7 +121,9 @@ public class Rfc3492Idn implements Idn {
|
|||
} else {
|
||||
t = k - bias;
|
||||
}
|
||||
if (digit < t) break;
|
||||
if (digit < t) {
|
||||
break;
|
||||
}
|
||||
w = w * (base - t); // FIXME fail on overflow
|
||||
}
|
||||
bias = adapt(i - oldi, output.length() + 1, (oldi == 0));
|
||||
|
|
|
@ -88,8 +88,9 @@ public class BasicManagedEntity extends HttpEntityWrapper
|
|||
}
|
||||
|
||||
private void ensureConsumed() throws IOException {
|
||||
if (managedConn == null)
|
||||
return;
|
||||
if (managedConn == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (attemptReuse) {
|
||||
|
|
|
@ -195,10 +195,12 @@ public class EofSensorInputStream extends InputStream implements ConnectionRelea
|
|||
if ((wrappedStream != null) && (eof < 0)) {
|
||||
try {
|
||||
boolean scws = true; // should close wrapped stream?
|
||||
if (eofWatcher != null)
|
||||
scws = eofWatcher.eofDetected(wrappedStream);
|
||||
if (scws)
|
||||
wrappedStream.close();
|
||||
if (eofWatcher != null) {
|
||||
scws = eofWatcher.eofDetected(wrappedStream);
|
||||
}
|
||||
if (scws) {
|
||||
wrappedStream.close();
|
||||
}
|
||||
} finally {
|
||||
wrappedStream = null;
|
||||
}
|
||||
|
@ -221,10 +223,12 @@ public class EofSensorInputStream extends InputStream implements ConnectionRelea
|
|||
if (wrappedStream != null) {
|
||||
try {
|
||||
boolean scws = true; // should close wrapped stream?
|
||||
if (eofWatcher != null)
|
||||
scws = eofWatcher.streamClosed(wrappedStream);
|
||||
if (scws)
|
||||
wrappedStream.close();
|
||||
if (eofWatcher != null) {
|
||||
scws = eofWatcher.streamClosed(wrappedStream);
|
||||
}
|
||||
if (scws) {
|
||||
wrappedStream.close();
|
||||
}
|
||||
} finally {
|
||||
wrappedStream = null;
|
||||
}
|
||||
|
@ -249,10 +253,12 @@ public class EofSensorInputStream extends InputStream implements ConnectionRelea
|
|||
if (wrappedStream != null) {
|
||||
try {
|
||||
boolean scws = true; // should close wrapped stream?
|
||||
if (eofWatcher != null)
|
||||
scws = eofWatcher.streamAbort(wrappedStream);
|
||||
if (scws)
|
||||
wrappedStream.close();
|
||||
if (eofWatcher != null) {
|
||||
scws = eofWatcher.streamAbort(wrappedStream);
|
||||
}
|
||||
if (scws) {
|
||||
wrappedStream.close();
|
||||
}
|
||||
} finally {
|
||||
wrappedStream = null;
|
||||
}
|
||||
|
|
|
@ -110,14 +110,17 @@ public final class MultihomePlainSocketFactory implements SocketFactory {
|
|||
Args.notNull(host, "Target host");
|
||||
Args.notNull(params, "HTTP parameters");
|
||||
|
||||
if (sock == null)
|
||||
sock = createSocket();
|
||||
if (sock == null) {
|
||||
sock = createSocket();
|
||||
}
|
||||
|
||||
if ((localAddress != null) || (localPort > 0)) {
|
||||
|
||||
// we need to bind explicitly
|
||||
if (localPort < 0)
|
||||
localPort = 0; // indicates "any"
|
||||
{
|
||||
localPort = 0; // indicates "any"
|
||||
}
|
||||
|
||||
InetSocketAddress isa =
|
||||
new InetSocketAddress(localAddress, localPort);
|
||||
|
|
|
@ -55,12 +55,13 @@ public class BasicRouteDirector implements HttpRouteDirector {
|
|||
|
||||
int step = UNREACHABLE;
|
||||
|
||||
if ((fact == null) || (fact.getHopCount() < 1))
|
||||
step = firstStep(plan);
|
||||
else if (plan.getHopCount() > 1)
|
||||
step = proxiedStep(plan, fact);
|
||||
else
|
||||
step = directStep(plan, fact);
|
||||
if ((fact == null) || (fact.getHopCount() < 1)) {
|
||||
step = firstStep(plan);
|
||||
} else if (plan.getHopCount() > 1) {
|
||||
step = proxiedStep(plan, fact);
|
||||
} else {
|
||||
step = directStep(plan, fact);
|
||||
}
|
||||
|
||||
return step;
|
||||
|
||||
|
@ -92,25 +93,30 @@ public class BasicRouteDirector implements HttpRouteDirector {
|
|||
*/
|
||||
protected int directStep(RouteInfo plan, RouteInfo fact) {
|
||||
|
||||
if (fact.getHopCount() > 1)
|
||||
return UNREACHABLE;
|
||||
if (fact.getHopCount() > 1) {
|
||||
return UNREACHABLE;
|
||||
}
|
||||
if (!plan.getTargetHost().equals(fact.getTargetHost()))
|
||||
return UNREACHABLE;
|
||||
{
|
||||
return UNREACHABLE;
|
||||
// If the security is too low, we could now suggest to layer
|
||||
// a secure protocol on the direct connection. Layering on direct
|
||||
// connections has not been supported in HttpClient 3.x, we don't
|
||||
// consider it here until there is a real-life use case for it.
|
||||
}
|
||||
|
||||
// Should we tolerate if security is better than planned?
|
||||
// (plan.isSecure() && !fact.isSecure())
|
||||
if (plan.isSecure() != fact.isSecure())
|
||||
return UNREACHABLE;
|
||||
if (plan.isSecure() != fact.isSecure()) {
|
||||
return UNREACHABLE;
|
||||
}
|
||||
|
||||
// Local address has to match only if the plan specifies one.
|
||||
if ((plan.getLocalAddress() != null) &&
|
||||
!plan.getLocalAddress().equals(fact.getLocalAddress())
|
||||
)
|
||||
return UNREACHABLE;
|
||||
) {
|
||||
return UNREACHABLE;
|
||||
}
|
||||
|
||||
return COMPLETE;
|
||||
}
|
||||
|
@ -127,38 +133,48 @@ public class BasicRouteDirector implements HttpRouteDirector {
|
|||
*/
|
||||
protected int proxiedStep(RouteInfo plan, RouteInfo fact) {
|
||||
|
||||
if (fact.getHopCount() <= 1)
|
||||
return UNREACHABLE;
|
||||
if (!plan.getTargetHost().equals(fact.getTargetHost()))
|
||||
return UNREACHABLE;
|
||||
if (fact.getHopCount() <= 1) {
|
||||
return UNREACHABLE;
|
||||
}
|
||||
if (!plan.getTargetHost().equals(fact.getTargetHost())) {
|
||||
return UNREACHABLE;
|
||||
}
|
||||
final int phc = plan.getHopCount();
|
||||
final int fhc = fact.getHopCount();
|
||||
if (phc < fhc)
|
||||
return UNREACHABLE;
|
||||
if (phc < fhc) {
|
||||
return UNREACHABLE;
|
||||
}
|
||||
|
||||
for (int i=0; i<fhc-1; i++) {
|
||||
if (!plan.getHopTarget(i).equals(fact.getHopTarget(i)))
|
||||
return UNREACHABLE;
|
||||
if (!plan.getHopTarget(i).equals(fact.getHopTarget(i))) {
|
||||
return UNREACHABLE;
|
||||
}
|
||||
}
|
||||
// now we know that the target matches and proxies so far are the same
|
||||
if (phc > fhc)
|
||||
return TUNNEL_PROXY; // need to extend the proxy chain
|
||||
{
|
||||
return TUNNEL_PROXY; // need to extend the proxy chain
|
||||
}
|
||||
|
||||
// proxy chain and target are the same, check tunnelling and layering
|
||||
if ((fact.isTunnelled() && !plan.isTunnelled()) ||
|
||||
(fact.isLayered() && !plan.isLayered()))
|
||||
return UNREACHABLE;
|
||||
(fact.isLayered() && !plan.isLayered())) {
|
||||
return UNREACHABLE;
|
||||
}
|
||||
|
||||
if (plan.isTunnelled() && !fact.isTunnelled())
|
||||
return TUNNEL_TARGET;
|
||||
if (plan.isLayered() && !fact.isLayered())
|
||||
return LAYER_PROTOCOL;
|
||||
if (plan.isTunnelled() && !fact.isTunnelled()) {
|
||||
return TUNNEL_TARGET;
|
||||
}
|
||||
if (plan.isLayered() && !fact.isLayered()) {
|
||||
return LAYER_PROTOCOL;
|
||||
}
|
||||
|
||||
// tunnel and layering are the same, remains to check the security
|
||||
// Should we tolerate if security is better than planned?
|
||||
// (plan.isSecure() && !fact.isSecure())
|
||||
if (plan.isSecure() != fact.isSecure())
|
||||
return UNREACHABLE;
|
||||
if (plan.isSecure() != fact.isSecure()) {
|
||||
return UNREACHABLE;
|
||||
}
|
||||
|
||||
return COMPLETE;
|
||||
}
|
||||
|
|
|
@ -101,10 +101,12 @@ public final class HttpRoute implements RouteInfo, Cloneable {
|
|||
Args.check(proxies.length > 0, "Proxy required if tunnelled");
|
||||
}
|
||||
// tunnelled is already checked above, that is in line with the default
|
||||
if (tunnelled == null)
|
||||
tunnelled = TunnelType.PLAIN;
|
||||
if (layered == null)
|
||||
layered = LayerType.PLAIN;
|
||||
if (tunnelled == null) {
|
||||
tunnelled = TunnelType.PLAIN;
|
||||
}
|
||||
if (layered == null) {
|
||||
layered = LayerType.PLAIN;
|
||||
}
|
||||
|
||||
this.targetHost = target;
|
||||
this.localAddress = local;
|
||||
|
@ -212,8 +214,9 @@ public final class HttpRoute implements RouteInfo, Cloneable {
|
|||
* @return a proxy chain array, may be empty (never null)
|
||||
*/
|
||||
private static HttpHost[] toChain(HttpHost proxy) {
|
||||
if (proxy == null)
|
||||
return EMPTY_HTTP_HOST_ARRAY;
|
||||
if (proxy == null) {
|
||||
return EMPTY_HTTP_HOST_ARRAY;
|
||||
}
|
||||
|
||||
return new HttpHost[]{ proxy };
|
||||
}
|
||||
|
@ -228,8 +231,9 @@ public final class HttpRoute implements RouteInfo, Cloneable {
|
|||
* @return a new proxy chain array, may be empty (never null)
|
||||
*/
|
||||
private static HttpHost[] toChain(HttpHost[] proxies) {
|
||||
if ((proxies == null) || (proxies.length < 1))
|
||||
return EMPTY_HTTP_HOST_ARRAY;
|
||||
if ((proxies == null) || (proxies.length < 1)) {
|
||||
return EMPTY_HTTP_HOST_ARRAY;
|
||||
}
|
||||
// copy the proxy chain, the traditional way
|
||||
HttpHost[] result = new HttpHost[proxies.length];
|
||||
System.arraycopy(proxies, 0, result, 0, proxies.length);
|
||||
|
@ -262,10 +266,11 @@ public final class HttpRoute implements RouteInfo, Cloneable {
|
|||
Args.check(hop < hopcount, "Hop index exceeds tracked route length");
|
||||
|
||||
HttpHost result = null;
|
||||
if (hop < hopcount-1)
|
||||
result = this.proxyChain[hop];
|
||||
else
|
||||
result = this.targetHost;
|
||||
if (hop < hopcount-1) {
|
||||
result = this.proxyChain[hop];
|
||||
} else {
|
||||
result = this.targetHost;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
@ -311,7 +316,9 @@ public final class HttpRoute implements RouteInfo, Cloneable {
|
|||
*/
|
||||
@Override
|
||||
public final boolean equals(Object obj) {
|
||||
if (this == obj) return true;
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj instanceof HttpRoute) {
|
||||
HttpRoute that = (HttpRoute) obj;
|
||||
return
|
||||
|
@ -361,12 +368,15 @@ public final class HttpRoute implements RouteInfo, Cloneable {
|
|||
cab.append("->");
|
||||
}
|
||||
cab.append('{');
|
||||
if (this.tunnelled == TunnelType.TUNNELLED)
|
||||
cab.append('t');
|
||||
if (this.layered == LayerType.LAYERED)
|
||||
cab.append('l');
|
||||
if (this.secure)
|
||||
cab.append('s');
|
||||
if (this.tunnelled == TunnelType.TUNNELLED) {
|
||||
cab.append('t');
|
||||
}
|
||||
if (this.layered == LayerType.LAYERED) {
|
||||
cab.append('l');
|
||||
}
|
||||
if (this.secure) {
|
||||
cab.append('s');
|
||||
}
|
||||
cab.append("}->");
|
||||
for (HttpHost aProxyChain : this.proxyChain) {
|
||||
cab.append(aProxyChain);
|
||||
|
|
|
@ -196,10 +196,11 @@ public final class RouteTracker implements RouteInfo, Cloneable {
|
|||
public final int getHopCount() {
|
||||
int hops = 0;
|
||||
if (this.connected) {
|
||||
if (proxyChain == null)
|
||||
hops = 1;
|
||||
else
|
||||
hops = proxyChain.length + 1;
|
||||
if (proxyChain == null) {
|
||||
hops = 1;
|
||||
} else {
|
||||
hops = proxyChain.length + 1;
|
||||
}
|
||||
}
|
||||
return hops;
|
||||
}
|
||||
|
@ -209,10 +210,11 @@ public final class RouteTracker implements RouteInfo, Cloneable {
|
|||
final int hopcount = getHopCount();
|
||||
Args.check(hop < hopcount, "Hop index exceeds tracked route length");
|
||||
HttpHost result = null;
|
||||
if (hop < hopcount-1)
|
||||
result = this.proxyChain[hop];
|
||||
else
|
||||
result = this.targetHost;
|
||||
if (hop < hopcount-1) {
|
||||
result = this.proxyChain[hop];
|
||||
} else {
|
||||
result = this.targetHost;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
@ -270,10 +272,12 @@ public final class RouteTracker implements RouteInfo, Cloneable {
|
|||
*/
|
||||
@Override
|
||||
public final boolean equals(Object o) {
|
||||
if (o == this)
|
||||
return true;
|
||||
if (!(o instanceof RouteTracker))
|
||||
return false;
|
||||
if (o == this) {
|
||||
return true;
|
||||
}
|
||||
if (!(o instanceof RouteTracker)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
RouteTracker that = (RouteTracker) o;
|
||||
return
|
||||
|
@ -327,14 +331,18 @@ public final class RouteTracker implements RouteInfo, Cloneable {
|
|||
cab.append("->");
|
||||
}
|
||||
cab.append('{');
|
||||
if (this.connected)
|
||||
cab.append('c');
|
||||
if (this.tunnelled == TunnelType.TUNNELLED)
|
||||
cab.append('t');
|
||||
if (this.layered == LayerType.LAYERED)
|
||||
cab.append('l');
|
||||
if (this.secure)
|
||||
cab.append('s');
|
||||
if (this.connected) {
|
||||
cab.append('c');
|
||||
}
|
||||
if (this.tunnelled == TunnelType.TUNNELLED) {
|
||||
cab.append('t');
|
||||
}
|
||||
if (this.layered == LayerType.LAYERED) {
|
||||
cab.append('l');
|
||||
}
|
||||
if (this.secure) {
|
||||
cab.append('s');
|
||||
}
|
||||
cab.append("}->");
|
||||
if (this.proxyChain != null) {
|
||||
for (HttpHost element : this.proxyChain) {
|
||||
|
|
|
@ -237,7 +237,9 @@ public final class Scheme {
|
|||
|
||||
@Override
|
||||
public final boolean equals(Object obj) {
|
||||
if (this == obj) return true;
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj instanceof Scheme) {
|
||||
Scheme that = (Scheme) obj;
|
||||
return this.name.equals(that.name)
|
||||
|
|
|
@ -79,8 +79,12 @@ class SchemeSocketFactoryAdaptor implements SchemeSocketFactory {
|
|||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (obj == null) return false;
|
||||
if (this == obj) return true;
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj instanceof SchemeSocketFactoryAdaptor) {
|
||||
return this.factory.equals(((SchemeSocketFactoryAdaptor)obj).factory);
|
||||
} else {
|
||||
|
|
|
@ -83,8 +83,12 @@ class SocketFactoryAdaptor implements SocketFactory {
|
|||
|
||||
@Override
|
||||
public boolean equals(final Object obj) {
|
||||
if (obj == null) return false;
|
||||
if (this == obj) return true;
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj instanceof SocketFactoryAdaptor) {
|
||||
return this.factory.equals(((SocketFactoryAdaptor)obj).factory);
|
||||
} else {
|
||||
|
|
|
@ -161,14 +161,17 @@ public abstract class GGSSchemeBase extends AuthSchemeBase {
|
|||
} catch (GSSException gsse) {
|
||||
state = State.FAILED;
|
||||
if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL
|
||||
|| gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED)
|
||||
throw new InvalidCredentialsException(gsse.getMessage(), gsse);
|
||||
if (gsse.getMajor() == GSSException.NO_CRED )
|
||||
throw new InvalidCredentialsException(gsse.getMessage(), gsse);
|
||||
|| gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) {
|
||||
throw new InvalidCredentialsException(gsse.getMessage(), gsse);
|
||||
}
|
||||
if (gsse.getMajor() == GSSException.NO_CRED ) {
|
||||
throw new InvalidCredentialsException(gsse.getMessage(), gsse);
|
||||
}
|
||||
if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN
|
||||
|| gsse.getMajor() == GSSException.DUPLICATE_TOKEN
|
||||
|| gsse.getMajor() == GSSException.OLD_TOKEN)
|
||||
throw new AuthenticationException(gsse.getMessage(), gsse);
|
||||
|| gsse.getMajor() == GSSException.OLD_TOKEN) {
|
||||
throw new AuthenticationException(gsse.getMessage(), gsse);
|
||||
}
|
||||
// other error
|
||||
throw new AuthenticationException(gsse.getMessage());
|
||||
}
|
||||
|
|
|
@ -185,8 +185,9 @@ final class NTLMEngineImpl implements NTLMEngine {
|
|||
/** Strip dot suffix from a name */
|
||||
private static String stripDotSuffix(String value) {
|
||||
int index = value.indexOf(".");
|
||||
if (index != -1)
|
||||
return value.substring(0, index);
|
||||
if (index != -1) {
|
||||
return value.substring(0, index);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
|
@ -201,24 +202,27 @@ final class NTLMEngineImpl implements NTLMEngine {
|
|||
}
|
||||
|
||||
private static int readULong(byte[] src, int index) throws NTLMEngineException {
|
||||
if (src.length < index + 4)
|
||||
throw new NTLMEngineException("NTLM authentication - buffer too small for DWORD");
|
||||
if (src.length < index + 4) {
|
||||
throw new NTLMEngineException("NTLM authentication - buffer too small for DWORD");
|
||||
}
|
||||
return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8)
|
||||
| ((src[index + 2] & 0xff) << 16) | ((src[index + 3] & 0xff) << 24);
|
||||
}
|
||||
|
||||
private static int readUShort(byte[] src, int index) throws NTLMEngineException {
|
||||
if (src.length < index + 2)
|
||||
throw new NTLMEngineException("NTLM authentication - buffer too small for WORD");
|
||||
if (src.length < index + 2) {
|
||||
throw new NTLMEngineException("NTLM authentication - buffer too small for WORD");
|
||||
}
|
||||
return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8);
|
||||
}
|
||||
|
||||
private static byte[] readSecurityBuffer(byte[] src, int index) throws NTLMEngineException {
|
||||
int length = readUShort(src, index);
|
||||
int offset = readULong(src, index + 4);
|
||||
if (src.length < offset + length)
|
||||
throw new NTLMEngineException(
|
||||
if (src.length < offset + length) {
|
||||
throw new NTLMEngineException(
|
||||
"NTLM authentication - buffer too small for data item");
|
||||
}
|
||||
byte[] buffer = new byte[length];
|
||||
System.arraycopy(src, offset, buffer, 0, length);
|
||||
return buffer;
|
||||
|
@ -299,56 +303,63 @@ final class NTLMEngineImpl implements NTLMEngine {
|
|||
/** Calculate and return client challenge */
|
||||
public byte[] getClientChallenge()
|
||||
throws NTLMEngineException {
|
||||
if (clientChallenge == null)
|
||||
clientChallenge = makeRandomChallenge();
|
||||
if (clientChallenge == null) {
|
||||
clientChallenge = makeRandomChallenge();
|
||||
}
|
||||
return clientChallenge;
|
||||
}
|
||||
|
||||
/** Calculate and return random secondary key */
|
||||
public byte[] getSecondaryKey()
|
||||
throws NTLMEngineException {
|
||||
if (secondaryKey == null)
|
||||
secondaryKey = makeSecondaryKey();
|
||||
if (secondaryKey == null) {
|
||||
secondaryKey = makeSecondaryKey();
|
||||
}
|
||||
return secondaryKey;
|
||||
}
|
||||
|
||||
/** Calculate and return the LMHash */
|
||||
public byte[] getLMHash()
|
||||
throws NTLMEngineException {
|
||||
if (lmHash == null)
|
||||
lmHash = lmHash(password);
|
||||
if (lmHash == null) {
|
||||
lmHash = lmHash(password);
|
||||
}
|
||||
return lmHash;
|
||||
}
|
||||
|
||||
/** Calculate and return the LMResponse */
|
||||
public byte[] getLMResponse()
|
||||
throws NTLMEngineException {
|
||||
if (lmResponse == null)
|
||||
lmResponse = lmResponse(getLMHash(),challenge);
|
||||
if (lmResponse == null) {
|
||||
lmResponse = lmResponse(getLMHash(),challenge);
|
||||
}
|
||||
return lmResponse;
|
||||
}
|
||||
|
||||
/** Calculate and return the NTLMHash */
|
||||
public byte[] getNTLMHash()
|
||||
throws NTLMEngineException {
|
||||
if (ntlmHash == null)
|
||||
ntlmHash = ntlmHash(password);
|
||||
if (ntlmHash == null) {
|
||||
ntlmHash = ntlmHash(password);
|
||||
}
|
||||
return ntlmHash;
|
||||
}
|
||||
|
||||
/** Calculate and return the NTLMResponse */
|
||||
public byte[] getNTLMResponse()
|
||||
throws NTLMEngineException {
|
||||
if (ntlmResponse == null)
|
||||
ntlmResponse = lmResponse(getNTLMHash(),challenge);
|
||||
if (ntlmResponse == null) {
|
||||
ntlmResponse = lmResponse(getNTLMHash(),challenge);
|
||||
}
|
||||
return ntlmResponse;
|
||||
}
|
||||
|
||||
/** Calculate the NTLMv2 hash */
|
||||
public byte[] getNTLMv2Hash()
|
||||
throws NTLMEngineException {
|
||||
if (ntlmv2Hash == null)
|
||||
ntlmv2Hash = ntlmv2Hash(target, user, password);
|
||||
if (ntlmv2Hash == null) {
|
||||
ntlmv2Hash = ntlmv2Hash(target, user, password);
|
||||
}
|
||||
return ntlmv2Hash;
|
||||
}
|
||||
|
||||
|
@ -371,32 +382,36 @@ final class NTLMEngineImpl implements NTLMEngine {
|
|||
/** Calculate the NTLMv2Blob */
|
||||
public byte[] getNTLMv2Blob()
|
||||
throws NTLMEngineException {
|
||||
if (ntlmv2Blob == null)
|
||||
ntlmv2Blob = createBlob(getClientChallenge(), targetInformation, getTimestamp());
|
||||
if (ntlmv2Blob == null) {
|
||||
ntlmv2Blob = createBlob(getClientChallenge(), targetInformation, getTimestamp());
|
||||
}
|
||||
return ntlmv2Blob;
|
||||
}
|
||||
|
||||
/** Calculate the NTLMv2Response */
|
||||
public byte[] getNTLMv2Response()
|
||||
throws NTLMEngineException {
|
||||
if (ntlmv2Response == null)
|
||||
ntlmv2Response = lmv2Response(getNTLMv2Hash(),challenge,getNTLMv2Blob());
|
||||
if (ntlmv2Response == null) {
|
||||
ntlmv2Response = lmv2Response(getNTLMv2Hash(),challenge,getNTLMv2Blob());
|
||||
}
|
||||
return ntlmv2Response;
|
||||
}
|
||||
|
||||
/** Calculate the LMv2Response */
|
||||
public byte[] getLMv2Response()
|
||||
throws NTLMEngineException {
|
||||
if (lmv2Response == null)
|
||||
lmv2Response = lmv2Response(getNTLMv2Hash(),challenge,getClientChallenge());
|
||||
if (lmv2Response == null) {
|
||||
lmv2Response = lmv2Response(getNTLMv2Hash(),challenge,getClientChallenge());
|
||||
}
|
||||
return lmv2Response;
|
||||
}
|
||||
|
||||
/** Get NTLM2SessionResponse */
|
||||
public byte[] getNTLM2SessionResponse()
|
||||
throws NTLMEngineException {
|
||||
if (ntlm2SessionResponse == null)
|
||||
ntlm2SessionResponse = ntlm2SessionResponse(getNTLMHash(),challenge,getClientChallenge());
|
||||
if (ntlm2SessionResponse == null) {
|
||||
ntlm2SessionResponse = ntlm2SessionResponse(getNTLMHash(),challenge,getClientChallenge());
|
||||
}
|
||||
return ntlm2SessionResponse;
|
||||
}
|
||||
|
||||
|
@ -557,8 +572,9 @@ final class NTLMEngineImpl implements NTLMEngine {
|
|||
System.arraycopy(digest, 0, sessionHash, 0, 8);
|
||||
return lmResponse(ntlmHash, sessionHash);
|
||||
} catch (Exception e) {
|
||||
if (e instanceof NTLMEngineException)
|
||||
throw (NTLMEngineException) e;
|
||||
if (e instanceof NTLMEngineException) {
|
||||
throw (NTLMEngineException) e;
|
||||
}
|
||||
throw new NTLMEngineException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
@ -802,21 +818,24 @@ final class NTLMEngineImpl implements NTLMEngine {
|
|||
messageContents = Base64.decodeBase64(EncodingUtils.getBytes(messageBody,
|
||||
DEFAULT_CHARSET));
|
||||
// Look for NTLM message
|
||||
if (messageContents.length < SIGNATURE.length)
|
||||
throw new NTLMEngineException("NTLM message decoding error - packet too short");
|
||||
if (messageContents.length < SIGNATURE.length) {
|
||||
throw new NTLMEngineException("NTLM message decoding error - packet too short");
|
||||
}
|
||||
int i = 0;
|
||||
while (i < SIGNATURE.length) {
|
||||
if (messageContents[i] != SIGNATURE[i])
|
||||
throw new NTLMEngineException(
|
||||
if (messageContents[i] != SIGNATURE[i]) {
|
||||
throw new NTLMEngineException(
|
||||
"NTLM message expected - instead got unrecognized bytes");
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
// Check to be sure there's a type 2 message indicator next
|
||||
int type = readULong(SIGNATURE.length);
|
||||
if (type != expectedType)
|
||||
throw new NTLMEngineException("NTLM type " + Integer.toString(expectedType)
|
||||
if (type != expectedType) {
|
||||
throw new NTLMEngineException("NTLM type " + Integer.toString(expectedType)
|
||||
+ " message expected - instead got type " + Integer.toString(type));
|
||||
}
|
||||
|
||||
currentOutputPosition = messageContents.length;
|
||||
}
|
||||
|
@ -836,15 +855,17 @@ final class NTLMEngineImpl implements NTLMEngine {
|
|||
|
||||
/** Read a byte from a position within the message buffer */
|
||||
protected byte readByte(int position) throws NTLMEngineException {
|
||||
if (messageContents.length < position + 1)
|
||||
throw new NTLMEngineException("NTLM: Message too short");
|
||||
if (messageContents.length < position + 1) {
|
||||
throw new NTLMEngineException("NTLM: Message too short");
|
||||
}
|
||||
return messageContents[position];
|
||||
}
|
||||
|
||||
/** Read a bunch of bytes from a position in the message buffer */
|
||||
protected void readBytes(byte[] buffer, int position) throws NTLMEngineException {
|
||||
if (messageContents.length < position + buffer.length)
|
||||
throw new NTLMEngineException("NTLM: Message too short");
|
||||
if (messageContents.length < position + buffer.length) {
|
||||
throw new NTLMEngineException("NTLM: Message too short");
|
||||
}
|
||||
System.arraycopy(messageContents, position, buffer, 0, buffer.length);
|
||||
}
|
||||
|
||||
|
@ -1062,10 +1083,11 @@ final class NTLMEngineImpl implements NTLMEngine {
|
|||
|
||||
flags = readULong(20);
|
||||
|
||||
if ((flags & FLAG_REQUEST_UNICODE_ENCODING) == 0)
|
||||
throw new NTLMEngineException(
|
||||
if ((flags & FLAG_REQUEST_UNICODE_ENCODING) == 0) {
|
||||
throw new NTLMEngineException(
|
||||
"NTLM type 2 message has flags that make no sense: "
|
||||
+ Integer.toString(flags));
|
||||
}
|
||||
|
||||
// Do the target!
|
||||
target = null;
|
||||
|
@ -1156,31 +1178,35 @@ final class NTLMEngineImpl implements NTLMEngine {
|
|||
// NTLMv2
|
||||
ntResp = gen.getNTLMv2Response();
|
||||
lmResp = gen.getLMv2Response();
|
||||
if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0)
|
||||
userSessionKey = gen.getLanManagerSessionKey();
|
||||
else
|
||||
userSessionKey = gen.getNTLMv2UserSessionKey();
|
||||
if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) {
|
||||
userSessionKey = gen.getLanManagerSessionKey();
|
||||
} else {
|
||||
userSessionKey = gen.getNTLMv2UserSessionKey();
|
||||
}
|
||||
} else {
|
||||
// NTLMv1
|
||||
if ((type2Flags & FLAG_REQUEST_NTLM2_SESSION) != 0) {
|
||||
// NTLM2 session stuff is requested
|
||||
ntResp = gen.getNTLM2SessionResponse();
|
||||
lmResp = gen.getLM2SessionResponse();
|
||||
if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0)
|
||||
userSessionKey = gen.getLanManagerSessionKey();
|
||||
else
|
||||
userSessionKey = gen.getNTLM2SessionResponseUserSessionKey();
|
||||
if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) {
|
||||
userSessionKey = gen.getLanManagerSessionKey();
|
||||
}
|
||||
else {
|
||||
userSessionKey = gen.getNTLM2SessionResponseUserSessionKey();
|
||||
// All the other flags we send (signing, sealing, key
|
||||
// exchange) are supported, but they don't do anything
|
||||
// at all in an
|
||||
// NTLM2 context! So we're done at this point.
|
||||
}
|
||||
} else {
|
||||
ntResp = gen.getNTLMResponse();
|
||||
lmResp = gen.getLMResponse();
|
||||
if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0)
|
||||
userSessionKey = gen.getLanManagerSessionKey();
|
||||
else
|
||||
userSessionKey = gen.getNTLMUserSessionKey();
|
||||
if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) {
|
||||
userSessionKey = gen.getLanManagerSessionKey();
|
||||
} else {
|
||||
userSessionKey = gen.getNTLMUserSessionKey();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (NTLMEngineException e) {
|
||||
|
@ -1188,16 +1214,18 @@ final class NTLMEngineImpl implements NTLMEngine {
|
|||
// fail back to just using LM
|
||||
ntResp = new byte[0];
|
||||
lmResp = gen.getLMResponse();
|
||||
if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0)
|
||||
userSessionKey = gen.getLanManagerSessionKey();
|
||||
else
|
||||
userSessionKey = gen.getLMUserSessionKey();
|
||||
if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) {
|
||||
userSessionKey = gen.getLanManagerSessionKey();
|
||||
} else {
|
||||
userSessionKey = gen.getLMUserSessionKey();
|
||||
}
|
||||
}
|
||||
|
||||
if ((type2Flags & FLAG_REQUEST_EXPLICIT_KEY_EXCH) != 0)
|
||||
sessionKey = RC4(gen.getSecondaryKey(), userSessionKey);
|
||||
else
|
||||
sessionKey = null;
|
||||
if ((type2Flags & FLAG_REQUEST_EXPLICIT_KEY_EXCH) != 0) {
|
||||
sessionKey = RC4(gen.getSecondaryKey(), userSessionKey);
|
||||
} else {
|
||||
sessionKey = null;
|
||||
}
|
||||
|
||||
try {
|
||||
domainBytes = domain.toUpperCase(Locale.US).getBytes("UnicodeLittleUnmarked");
|
||||
|
@ -1218,10 +1246,11 @@ final class NTLMEngineImpl implements NTLMEngine {
|
|||
int hostLen = hostBytes.length;
|
||||
int userLen = userBytes.length;
|
||||
int sessionKeyLen;
|
||||
if (sessionKey != null)
|
||||
sessionKeyLen = sessionKey.length;
|
||||
else
|
||||
sessionKeyLen = 0;
|
||||
if (sessionKey != null) {
|
||||
sessionKeyLen = sessionKey.length;
|
||||
} else {
|
||||
sessionKeyLen = 0;
|
||||
}
|
||||
|
||||
// Calculate the layout within the packet
|
||||
int lmRespOffset = 72; // allocate space for the version
|
||||
|
@ -1319,8 +1348,9 @@ final class NTLMEngineImpl implements NTLMEngine {
|
|||
addBytes(domainBytes);
|
||||
addBytes(userBytes);
|
||||
addBytes(hostBytes);
|
||||
if (sessionKey != null)
|
||||
addBytes(sessionKey);
|
||||
if (sessionKey != null) {
|
||||
addBytes(sessionKey);
|
||||
}
|
||||
|
||||
return super.getResponse();
|
||||
}
|
||||
|
|
|
@ -87,14 +87,18 @@ public class AIMDBackoffManager implements BackoffManager {
|
|||
int curr = connPerRoute.getMaxPerRoute(route);
|
||||
Long lastUpdate = getLastUpdate(lastRouteBackoffs, route);
|
||||
long now = clock.getCurrentTime();
|
||||
if (now - lastUpdate.longValue() < coolDown) return;
|
||||
if (now - lastUpdate.longValue() < coolDown) {
|
||||
return;
|
||||
}
|
||||
connPerRoute.setMaxPerRoute(route, getBackedOffPoolSize(curr));
|
||||
lastRouteBackoffs.put(route, Long.valueOf(now));
|
||||
}
|
||||
}
|
||||
|
||||
private int getBackedOffPoolSize(int curr) {
|
||||
if (curr <= 1) return 1;
|
||||
if (curr <= 1) {
|
||||
return 1;
|
||||
}
|
||||
return (int)(Math.floor(backoffFactor * curr));
|
||||
}
|
||||
|
||||
|
@ -105,8 +109,9 @@ public class AIMDBackoffManager implements BackoffManager {
|
|||
Long lastProbe = getLastUpdate(lastRouteProbes, route);
|
||||
Long lastBackoff = getLastUpdate(lastRouteBackoffs, route);
|
||||
long now = clock.getCurrentTime();
|
||||
if (now - lastProbe.longValue() < coolDown || now - lastBackoff.longValue() < coolDown)
|
||||
return;
|
||||
if (now - lastProbe.longValue() < coolDown || now - lastBackoff.longValue() < coolDown) {
|
||||
return;
|
||||
}
|
||||
connPerRoute.setMaxPerRoute(route, max);
|
||||
lastRouteProbes.put(route, Long.valueOf(now));
|
||||
}
|
||||
|
@ -114,7 +119,9 @@ public class AIMDBackoffManager implements BackoffManager {
|
|||
|
||||
private Long getLastUpdate(Map<HttpRoute,Long> updates, HttpRoute route) {
|
||||
Long lastUpdate = updates.get(route);
|
||||
if (lastUpdate == null) lastUpdate = Long.valueOf(0L);
|
||||
if (lastUpdate == null) {
|
||||
lastUpdate = Long.valueOf(0L);
|
||||
}
|
||||
return lastUpdate;
|
||||
}
|
||||
|
||||
|
|
|
@ -840,8 +840,12 @@ public abstract class AbstractHttpClient extends CloseableHttpClient {
|
|||
if (connectionBackoffStrategy.shouldBackoff(e)) {
|
||||
backoffManager.backOff(route);
|
||||
}
|
||||
if (e instanceof HttpException) throw (HttpException)e;
|
||||
if (e instanceof IOException) throw (IOException)e;
|
||||
if (e instanceof HttpException) {
|
||||
throw (HttpException)e;
|
||||
}
|
||||
if (e instanceof IOException) {
|
||||
throw (IOException)e;
|
||||
}
|
||||
throw new UndeclaredThrowableException(e);
|
||||
}
|
||||
if (connectionBackoffStrategy.shouldBackoff(out)) {
|
||||
|
|
|
@ -147,7 +147,9 @@ public class DecompressingHttpClient implements HttpClient {
|
|||
public HttpResponse execute(HttpHost target, HttpRequest request,
|
||||
HttpContext context) throws IOException, ClientProtocolException {
|
||||
try {
|
||||
if (context == null) context = new BasicHttpContext();
|
||||
if (context == null) {
|
||||
context = new BasicHttpContext();
|
||||
}
|
||||
HttpRequest wrapped;
|
||||
if (request instanceof HttpEntityEnclosingRequest) {
|
||||
wrapped = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request);
|
||||
|
@ -205,7 +207,9 @@ public class DecompressingHttpClient implements HttpClient {
|
|||
return responseHandler.handleResponse(response);
|
||||
} finally {
|
||||
HttpEntity entity = response.getEntity();
|
||||
if (entity != null) EntityUtils.consume(entity);
|
||||
if (entity != null) {
|
||||
EntityUtils.consume(entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -562,8 +562,9 @@ public class DefaultRequestDirector implements RequestDirector {
|
|||
if ((response == null) || (response.getEntity() == null) ||
|
||||
!response.getEntity().isStreaming()) {
|
||||
// connection not needed and (assumed to be) in re-usable state
|
||||
if (reuse)
|
||||
managedConn.markReusable();
|
||||
if (reuse) {
|
||||
managedConn.markReusable();
|
||||
}
|
||||
releaseConnection();
|
||||
} else {
|
||||
// install an auto-release entity
|
||||
|
|
|
@ -158,18 +158,21 @@ public abstract class AbstractClientConnAdapter implements ManagedClientConnecti
|
|||
|
||||
public boolean isOpen() {
|
||||
OperatedClientConnection conn = getWrappedConnection();
|
||||
if (conn == null)
|
||||
return false;
|
||||
if (conn == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return conn.isOpen();
|
||||
}
|
||||
|
||||
public boolean isStale() {
|
||||
if (isReleased())
|
||||
return true;
|
||||
if (isReleased()) {
|
||||
return true;
|
||||
}
|
||||
OperatedClientConnection conn = getWrappedConnection();
|
||||
if (conn == null)
|
||||
return true;
|
||||
if (conn == null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return conn.isStale();
|
||||
}
|
||||
|
@ -273,16 +276,18 @@ public abstract class AbstractClientConnAdapter implements ManagedClientConnecti
|
|||
public Socket getSocket() {
|
||||
OperatedClientConnection conn = getWrappedConnection();
|
||||
assertValid(conn);
|
||||
if (!isOpen())
|
||||
return null;
|
||||
if (!isOpen()) {
|
||||
return null;
|
||||
}
|
||||
return conn.getSocket();
|
||||
}
|
||||
|
||||
public SSLSession getSSLSession() {
|
||||
OperatedClientConnection conn = getWrappedConnection();
|
||||
assertValid(conn);
|
||||
if (!isOpen())
|
||||
return null;
|
||||
if (!isOpen()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
SSLSession result = null;
|
||||
Socket sock = conn.getSocket();
|
||||
|
|
|
@ -150,8 +150,9 @@ public abstract class AbstractPooledConnAdapter extends AbstractClientConnAdapte
|
|||
|
||||
public void close() throws IOException {
|
||||
AbstractPoolEntry entry = getPoolEntry();
|
||||
if (entry != null)
|
||||
entry.shutdownEntry();
|
||||
if (entry != null) {
|
||||
entry.shutdownEntry();
|
||||
}
|
||||
|
||||
OperatedClientConnection conn = getWrappedConnection();
|
||||
if (conn != null) {
|
||||
|
@ -161,8 +162,9 @@ public abstract class AbstractPooledConnAdapter extends AbstractClientConnAdapte
|
|||
|
||||
public void shutdown() throws IOException {
|
||||
AbstractPoolEntry entry = getPoolEntry();
|
||||
if (entry != null)
|
||||
entry.shutdownEntry();
|
||||
if (entry != null) {
|
||||
entry.shutdownEntry();
|
||||
}
|
||||
|
||||
OperatedClientConnection conn = getWrappedConnection();
|
||||
if (conn != null) {
|
||||
|
|
|
@ -156,8 +156,9 @@ public class DefaultClientConnection extends SocketHttpClientConnection
|
|||
log.debug("Connection " + this + " shut down");
|
||||
}
|
||||
Socket sock = this.socket; // copy volatile attribute
|
||||
if (sock != null)
|
||||
sock.close();
|
||||
if (sock != null) {
|
||||
sock.close();
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
log.debug("I/O error shutting down connection", ex);
|
||||
}
|
||||
|
|
|
@ -88,8 +88,9 @@ public class DefaultHttpRoutePlanner implements HttpRoutePlanner {
|
|||
// If we have a forced route, we can do without a target.
|
||||
HttpRoute route =
|
||||
ConnRouteParams.getForcedRoute(request.getParams());
|
||||
if (route != null)
|
||||
return route;
|
||||
if (route != null) {
|
||||
return route;
|
||||
}
|
||||
|
||||
// If we get here, there is no forced route.
|
||||
// So we need a target to compute a route.
|
||||
|
|
|
@ -124,8 +124,9 @@ public class ProxySelectorRoutePlanner implements HttpRoutePlanner {
|
|||
// If we have a forced route, we can do without a target.
|
||||
HttpRoute route =
|
||||
ConnRouteParams.getForcedRoute(request.getParams());
|
||||
if (route != null)
|
||||
return route;
|
||||
if (route != null) {
|
||||
return route;
|
||||
}
|
||||
|
||||
// If we get here, there is no forced route.
|
||||
// So we need a target to compute a route.
|
||||
|
@ -169,10 +170,12 @@ public class ProxySelectorRoutePlanner implements HttpRoutePlanner {
|
|||
|
||||
// the proxy selector can be 'unset', so we better deal with null here
|
||||
ProxySelector psel = this.proxySelector;
|
||||
if (psel == null)
|
||||
psel = ProxySelector.getDefault();
|
||||
if (psel == null)
|
||||
return null;
|
||||
if (psel == null) {
|
||||
psel = ProxySelector.getDefault();
|
||||
}
|
||||
if (psel == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
URI targetURI = null;
|
||||
try {
|
||||
|
|
|
@ -243,8 +243,9 @@ public class SingleClientConnManager implements ClientConnectionManager {
|
|||
}
|
||||
}
|
||||
|
||||
if (recreate)
|
||||
uniquePoolEntry = new PoolEntry();
|
||||
if (recreate) {
|
||||
uniquePoolEntry = new PoolEntry();
|
||||
}
|
||||
|
||||
managedConn = new ConnAdapter(uniquePoolEntry, route);
|
||||
|
||||
|
@ -266,7 +267,9 @@ public class SingleClientConnManager implements ClientConnectionManager {
|
|||
ConnAdapter sca = (ConnAdapter) conn;
|
||||
synchronized (sca) {
|
||||
if (sca.poolEntry == null)
|
||||
return; // already released
|
||||
{
|
||||
return; // already released
|
||||
}
|
||||
ClientConnectionManager manager = sca.getManager();
|
||||
Asserts.check(manager == this, "Connection not obtained from this manager");
|
||||
try {
|
||||
|
@ -285,18 +288,20 @@ public class SingleClientConnManager implements ClientConnectionManager {
|
|||
sca.shutdown();
|
||||
}
|
||||
} catch (IOException iox) {
|
||||
if (log.isDebugEnabled())
|
||||
log.debug("Exception shutting down released connection.",
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Exception shutting down released connection.",
|
||||
iox);
|
||||
}
|
||||
} finally {
|
||||
sca.detach();
|
||||
synchronized (this) {
|
||||
managedConn = null;
|
||||
lastReleaseTime = System.currentTimeMillis();
|
||||
if(validDuration > 0)
|
||||
connectionExpiresTime = timeUnit.toMillis(validDuration) + lastReleaseTime;
|
||||
else
|
||||
connectionExpiresTime = Long.MAX_VALUE;
|
||||
if(validDuration > 0) {
|
||||
connectionExpiresTime = timeUnit.toMillis(validDuration) + lastReleaseTime;
|
||||
} else {
|
||||
connectionExpiresTime = Long.MAX_VALUE;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -335,8 +340,9 @@ public class SingleClientConnManager implements ClientConnectionManager {
|
|||
this.isShutDown = true;
|
||||
synchronized (this) {
|
||||
try {
|
||||
if (uniquePoolEntry != null) // and connection open?
|
||||
uniquePoolEntry.shutdown();
|
||||
if (uniquePoolEntry != null) {
|
||||
uniquePoolEntry.shutdown();
|
||||
}
|
||||
} catch (IOException iox) {
|
||||
// ignore
|
||||
log.debug("Problem while shutting down manager.", iox);
|
||||
|
@ -349,8 +355,9 @@ public class SingleClientConnManager implements ClientConnectionManager {
|
|||
|
||||
protected void revokeConnection() {
|
||||
ConnAdapter conn = managedConn;
|
||||
if (conn == null)
|
||||
return;
|
||||
if (conn == null) {
|
||||
return;
|
||||
}
|
||||
conn.detach();
|
||||
|
||||
synchronized (this) {
|
||||
|
@ -381,8 +388,9 @@ public class SingleClientConnManager implements ClientConnectionManager {
|
|||
*/
|
||||
protected void close() throws IOException {
|
||||
shutdownEntry();
|
||||
if (connection.isOpen())
|
||||
connection.close();
|
||||
if (connection.isOpen()) {
|
||||
connection.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -390,8 +398,9 @@ public class SingleClientConnManager implements ClientConnectionManager {
|
|||
*/
|
||||
protected void shutdown() throws IOException {
|
||||
shutdownEntry();
|
||||
if (connection.isOpen())
|
||||
connection.shutdown();
|
||||
if (connection.isOpen()) {
|
||||
connection.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -194,8 +194,9 @@ public abstract class AbstractConnPool {
|
|||
poolLock.lock();
|
||||
try {
|
||||
|
||||
if (isShutDown)
|
||||
return;
|
||||
if (isShutDown) {
|
||||
return;
|
||||
}
|
||||
|
||||
// close all connections that are issued to an application
|
||||
Iterator<BasicPoolEntry> iter = leasedConnections.iterator();
|
||||
|
|
|
@ -499,9 +499,10 @@ public class ConnPoolByRoute extends AbstractConnPool {
|
|||
if (entry.isExpired(System.currentTimeMillis())) {
|
||||
// If the free entry isn't valid anymore, get rid of it
|
||||
// and loop to find another one that might be valid.
|
||||
if (log.isDebugEnabled())
|
||||
log.debug("Closing expired free connection"
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Closing expired free connection"
|
||||
+ " [" + rospl.getRoute() + "][" + state + "]");
|
||||
}
|
||||
closeConnection(entry);
|
||||
// We use dropEntry instead of deleteEntry because the entry
|
||||
// is no longer "free" (we just allocated it), and deleteEntry
|
||||
|
|
|
@ -242,8 +242,9 @@ public class RouteSpecificPool {
|
|||
public boolean deleteEntry(BasicPoolEntry entry) {
|
||||
|
||||
final boolean found = freeEntries.remove(entry);
|
||||
if (found)
|
||||
numEntries--;
|
||||
if (found) {
|
||||
numEntries--;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
|
@ -301,8 +302,9 @@ public class RouteSpecificPool {
|
|||
* @param wt the waiting thread
|
||||
*/
|
||||
public void removeThread(WaitingThread wt) {
|
||||
if (wt == null)
|
||||
return;
|
||||
if (wt == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.waitingThreads.remove(wt);
|
||||
}
|
||||
|
|
|
@ -270,9 +270,10 @@ public class ThreadSafeClientConnManager implements ClientConnectionManager {
|
|||
hca.shutdown();
|
||||
}
|
||||
} catch (IOException iox) {
|
||||
if (log.isDebugEnabled())
|
||||
log.debug("Exception shutting down released connection.",
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Exception shutting down released connection.",
|
||||
iox);
|
||||
}
|
||||
} finally {
|
||||
boolean reusable = hca.isMarkedReusable();
|
||||
if (log.isDebugEnabled()) {
|
||||
|
|
|
@ -145,8 +145,9 @@ public class WaitingThread {
|
|||
"\nwaiter: " + this.waiter);
|
||||
}
|
||||
|
||||
if (aborted)
|
||||
throw new InterruptedException("Operation interrupted");
|
||||
if (aborted) {
|
||||
throw new InterruptedException("Operation interrupted");
|
||||
}
|
||||
|
||||
this.waiter = Thread.currentThread();
|
||||
|
||||
|
@ -158,8 +159,9 @@ public class WaitingThread {
|
|||
this.cond.await();
|
||||
success = true;
|
||||
}
|
||||
if (aborted)
|
||||
throw new InterruptedException("Operation interrupted");
|
||||
if (aborted) {
|
||||
throw new InterruptedException("Operation interrupted");
|
||||
}
|
||||
} finally {
|
||||
this.waiter = null;
|
||||
}
|
||||
|
|
|
@ -47,8 +47,9 @@ public class WaitingThreadAborter {
|
|||
public void abort() {
|
||||
aborted = true;
|
||||
|
||||
if (waitingThread != null)
|
||||
waitingThread.interrupt();
|
||||
if (waitingThread != null) {
|
||||
waitingThread.interrupt();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
@ -60,8 +61,9 @@ public class WaitingThreadAborter {
|
|||
*/
|
||||
public void setWaitingThread(WaitingThread waitingThread) {
|
||||
this.waitingThread = waitingThread;
|
||||
if (aborted)
|
||||
waitingThread.interrupt();
|
||||
if (aborted) {
|
||||
waitingThread.interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -156,8 +156,9 @@ public final class DateUtils {
|
|||
dateParser.set2DigitYearStart(startDate);
|
||||
ParsePosition pos = new ParsePosition(0);
|
||||
Date result = dateParser.parse(dateValue, pos);
|
||||
if (pos.getIndex() != 0)
|
||||
return result;
|
||||
if (pos.getIndex() != 0) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
// we were unable to parse the date
|
||||
|
|
|
@ -79,7 +79,9 @@ public class PublicSuffixFilter implements CookieAttributeHandler {
|
|||
* Never matches if the cookie's domain is from the blacklist.
|
||||
*/
|
||||
public boolean match(Cookie cookie, CookieOrigin origin) {
|
||||
if (isForPublicSuffix(cookie)) return false;
|
||||
if (isForPublicSuffix(cookie)) {
|
||||
return false;
|
||||
}
|
||||
return wrapped.match(cookie, origin);
|
||||
}
|
||||
|
||||
|
@ -93,23 +95,35 @@ public class PublicSuffixFilter implements CookieAttributeHandler {
|
|||
|
||||
private boolean isForPublicSuffix(Cookie cookie) {
|
||||
String domain = cookie.getDomain();
|
||||
if (domain.startsWith(".")) domain = domain.substring(1);
|
||||
if (domain.startsWith(".")) {
|
||||
domain = domain.substring(1);
|
||||
}
|
||||
domain = Punycode.toUnicode(domain);
|
||||
|
||||
// An exception rule takes priority over any other matching rule.
|
||||
if (this.exceptions != null) {
|
||||
if (this.exceptions.contains(domain)) return false;
|
||||
if (this.exceptions.contains(domain)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (this.suffixes == null) return false;
|
||||
if (this.suffixes == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
do {
|
||||
if (this.suffixes.contains(domain)) return true;
|
||||
if (this.suffixes.contains(domain)) {
|
||||
return true;
|
||||
}
|
||||
// patterns
|
||||
if (domain.startsWith("*.")) domain = domain.substring(2);
|
||||
if (domain.startsWith("*.")) {
|
||||
domain = domain.substring(2);
|
||||
}
|
||||
int nextdot = domain.indexOf('.');
|
||||
if (nextdot == -1) break;
|
||||
if (nextdot == -1) {
|
||||
break;
|
||||
}
|
||||
domain = "*" + domain.substring(nextdot);
|
||||
} while (domain.length() > 0);
|
||||
|
||||
|
|
|
@ -66,12 +66,22 @@ public class PublicSuffixListParser {
|
|||
while (more) {
|
||||
more = readLine(r, sb);
|
||||
String line = sb.toString();
|
||||
if (line.length() == 0) continue;
|
||||
if (line.startsWith("//")) continue; //entire lines can also be commented using //
|
||||
if (line.startsWith(".")) line = line.substring(1); // A leading dot is optional
|
||||
if (line.length() == 0) {
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("//"))
|
||||
{
|
||||
continue; //entire lines can also be commented using //
|
||||
}
|
||||
if (line.startsWith("."))
|
||||
{
|
||||
line = line.substring(1); // A leading dot is optional
|
||||
}
|
||||
// An exclamation mark (!) at the start of a rule marks an exception to a previous wildcard rule
|
||||
boolean isException = line.startsWith("!");
|
||||
if (isException) line = line.substring(1);
|
||||
if (isException) {
|
||||
line = line.substring(1);
|
||||
}
|
||||
|
||||
if (isException) {
|
||||
exceptions.add(line);
|
||||
|
@ -97,11 +107,20 @@ public class PublicSuffixListParser {
|
|||
boolean hitWhitespace = false;
|
||||
while ((b = r.read()) != -1) {
|
||||
char c = (char) b;
|
||||
if (c == '\n') break;
|
||||
if (c == '\n') {
|
||||
break;
|
||||
}
|
||||
// Each line is only read up to the first whitespace
|
||||
if (Character.isWhitespace(c)) hitWhitespace = true;
|
||||
if (!hitWhitespace) sb.append(c);
|
||||
if (sb.length() > MAX_LINE_LEN) throw new IOException("Line too long"); // prevent excess memory usage
|
||||
if (Character.isWhitespace(c)) {
|
||||
hitWhitespace = true;
|
||||
}
|
||||
if (!hitWhitespace) {
|
||||
sb.append(c);
|
||||
}
|
||||
if (sb.length() > MAX_LINE_LEN)
|
||||
{
|
||||
throw new IOException("Line too long"); // prevent excess memory usage
|
||||
}
|
||||
}
|
||||
return (b != -1);
|
||||
}
|
||||
|
|
|
@ -82,9 +82,15 @@ public class BackoffStrategyExec implements ClientExecChain {
|
|||
if (this.connectionBackoffStrategy.shouldBackoff(ex)) {
|
||||
this.backoffManager.backOff(route);
|
||||
}
|
||||
if (ex instanceof RuntimeException) throw (RuntimeException) ex;
|
||||
if (ex instanceof HttpException) throw (HttpException) ex;
|
||||
if (ex instanceof IOException) throw (IOException) ex;
|
||||
if (ex instanceof RuntimeException) {
|
||||
throw (RuntimeException) ex;
|
||||
}
|
||||
if (ex instanceof HttpException) {
|
||||
throw (HttpException) ex;
|
||||
}
|
||||
if (ex instanceof IOException) {
|
||||
throw (IOException) ex;
|
||||
}
|
||||
throw new UndeclaredThrowableException(ex);
|
||||
}
|
||||
if (this.connectionBackoffStrategy.shouldBackoff(out)) {
|
||||
|
|
|
@ -137,12 +137,13 @@ public class TestScheme {
|
|||
boolean flaghttps = false;
|
||||
String name = names.get(0);
|
||||
|
||||
if ("http".equals(name))
|
||||
flaghttp = true;
|
||||
else if ("https".equals(name))
|
||||
flaghttps = true;
|
||||
else
|
||||
Assert.fail("unexpected name in iterator: " + name);
|
||||
if ("http".equals(name)) {
|
||||
flaghttp = true;
|
||||
} else if ("https".equals(name)) {
|
||||
flaghttps = true;
|
||||
} else {
|
||||
Assert.fail("unexpected name in iterator: " + name);
|
||||
}
|
||||
|
||||
Assert.assertNotNull(schmreg.get(name));
|
||||
schmreg.unregister(name);
|
||||
|
@ -151,9 +152,13 @@ public class TestScheme {
|
|||
name = names.get(1);
|
||||
|
||||
if ("http".equals(name)) {
|
||||
if (flaghttp) Assert.fail("name 'http' found twice");
|
||||
if (flaghttp) {
|
||||
Assert.fail("name 'http' found twice");
|
||||
}
|
||||
} else if ("https".equals(name)) {
|
||||
if (flaghttps) Assert.fail("name 'https' found twice");
|
||||
if (flaghttps) {
|
||||
Assert.fail("name 'https' found twice");
|
||||
}
|
||||
} else {
|
||||
Assert.fail("unexpected name in iterator: " + name);
|
||||
}
|
||||
|
|
|
@ -691,8 +691,9 @@ public class TestRouteTracker {
|
|||
* @return the result of <code>rt.toString()</code>
|
||||
*/
|
||||
public final static String checkToString(RouteTracker rt) {
|
||||
if (rt == null)
|
||||
return null;
|
||||
if (rt == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final String rts = rt.toString();
|
||||
|
||||
|
|
|
@ -47,8 +47,9 @@ public class TestNTLMEngineImpl {
|
|||
|
||||
/* Test suite helper */
|
||||
static byte toNibble(char c) {
|
||||
if (c >= 'a' && c <= 'f')
|
||||
return (byte) (c - 'a' + 0x0a);
|
||||
if (c >= 'a' && c <= 'f') {
|
||||
return (byte) (c - 'a' + 0x0a);
|
||||
}
|
||||
return (byte) (c - '0');
|
||||
}
|
||||
|
||||
|
@ -71,13 +72,15 @@ public class TestNTLMEngineImpl {
|
|||
md4.update(input.getBytes("ASCII"));
|
||||
byte[] answer = md4.getOutput();
|
||||
byte[] correctAnswer = toBytes(hexOutput);
|
||||
if (answer.length != correctAnswer.length)
|
||||
throw new Exception("Answer length disagrees for MD4('" + input + "')");
|
||||
if (answer.length != correctAnswer.length) {
|
||||
throw new Exception("Answer length disagrees for MD4('" + input + "')");
|
||||
}
|
||||
int i = 0;
|
||||
while (i < answer.length) {
|
||||
if (answer[i] != correctAnswer[i])
|
||||
throw new Exception("Answer value for MD4('" + input + "') disagrees at position "
|
||||
if (answer[i] != correctAnswer[i]) {
|
||||
throw new Exception("Answer value for MD4('" + input + "') disagrees at position "
|
||||
+ Integer.toString(i));
|
||||
}
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -159,8 +159,12 @@ public class TestAIMDBackoffManager {
|
|||
@Test
|
||||
public void coolDownPeriodIsConfigurable() {
|
||||
long cd = new Random().nextLong() / 2;
|
||||
if (cd < 0) cd *= -1;
|
||||
if (cd < 1) cd++;
|
||||
if (cd < 0) {
|
||||
cd *= -1;
|
||||
}
|
||||
if (cd < 1) {
|
||||
cd++;
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
impl.setCooldownMillis(cd);
|
||||
clock.setCurrentTime(now);
|
||||
|
|
|
@ -155,8 +155,12 @@ public class TestDecompressingHttpClient {
|
|||
boolean foundDeflate = false;
|
||||
for(Header h : captured.getHeaders("Accept-Encoding")) {
|
||||
for(HeaderElement elt : h.getElements()) {
|
||||
if ("gzip".equals(elt.getName())) foundGzip = true;
|
||||
if ("deflate".equals(elt.getName())) foundDeflate = true;
|
||||
if ("gzip".equals(elt.getName())) {
|
||||
foundGzip = true;
|
||||
}
|
||||
if ("deflate".equals(elt.getName())) {
|
||||
foundDeflate = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(foundGzip);
|
||||
|
|
|
@ -81,7 +81,9 @@ public class TestDefaultBackoffStrategy {
|
|||
@Test
|
||||
public void doesNotBackOffForNon503StatusCodes() {
|
||||
for(int i = 100; i <= 599; i++) {
|
||||
if (i == HttpStatus.SC_SERVICE_UNAVAILABLE) continue;
|
||||
if (i == HttpStatus.SC_SERVICE_UNAVAILABLE) {
|
||||
continue;
|
||||
}
|
||||
HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1,
|
||||
i, "Foo");
|
||||
assertFalse(impl.shouldBackoff(resp));
|
||||
|
|
|
@ -215,8 +215,9 @@ public class TestAbortHandling extends IntegrationTestBase {
|
|||
public void run() {
|
||||
try {
|
||||
try {
|
||||
if(!startLatch.await(1, TimeUnit.SECONDS))
|
||||
throw new RuntimeException("Took too long to start!");
|
||||
if(!startLatch.await(1, TimeUnit.SECONDS)) {
|
||||
throw new RuntimeException("Took too long to start!");
|
||||
}
|
||||
} catch(InterruptedException interrupted) {
|
||||
throw new RuntimeException("Never started!", interrupted);
|
||||
}
|
||||
|
@ -374,11 +375,13 @@ public class TestAbortHandling extends IntegrationTestBase {
|
|||
connLatch.countDown(); // notify waiter that we're getting a connection
|
||||
|
||||
// zero usually means sleep forever, but CountDownLatch doesn't interpret it that way.
|
||||
if(timeout == 0)
|
||||
timeout = Integer.MAX_VALUE;
|
||||
if(timeout == 0) {
|
||||
timeout = Integer.MAX_VALUE;
|
||||
}
|
||||
|
||||
if(!awaitLatch.await(timeout, tunit))
|
||||
throw new ConnectionPoolTimeoutException();
|
||||
if(!awaitLatch.await(timeout, tunit)) {
|
||||
throw new ConnectionPoolTimeoutException();
|
||||
}
|
||||
|
||||
return Mockito.mock(HttpClientConnection.class);
|
||||
}
|
||||
|
@ -432,11 +435,13 @@ public class TestAbortHandling extends IntegrationTestBase {
|
|||
connLatch.countDown(); // notify waiter that we're getting a connection
|
||||
|
||||
// zero usually means sleep forever, but CountDownLatch doesn't interpret it that way.
|
||||
if(timeout == 0)
|
||||
timeout = Integer.MAX_VALUE;
|
||||
if(timeout == 0) {
|
||||
timeout = Integer.MAX_VALUE;
|
||||
}
|
||||
|
||||
if(!awaitLatch.await(timeout, tunit))
|
||||
throw new ConnectionPoolTimeoutException();
|
||||
if(!awaitLatch.await(timeout, tunit)) {
|
||||
throw new ConnectionPoolTimeoutException();
|
||||
}
|
||||
|
||||
return Mockito.mock(HttpClientConnection.class);
|
||||
}
|
||||
|
@ -485,8 +490,9 @@ public class TestAbortHandling extends IntegrationTestBase {
|
|||
@Override
|
||||
public void setCancellable(Cancellable cancellable) {
|
||||
try {
|
||||
if(!releaseTriggerLatch.await(1, TimeUnit.SECONDS))
|
||||
throw new RuntimeException("Waited too long...");
|
||||
if(!releaseTriggerLatch.await(1, TimeUnit.SECONDS)) {
|
||||
throw new RuntimeException("Waited too long...");
|
||||
}
|
||||
} catch(InterruptedException ie) {
|
||||
throw new RuntimeException(ie);
|
||||
}
|
||||
|
|
|
@ -462,8 +462,9 @@ public class TestConnectionManagement extends LocalServerTestBase {
|
|||
} catch(SocketException expected) {}
|
||||
|
||||
abortingThread.join(5000);
|
||||
if(throwRef.get() != null)
|
||||
throw new RuntimeException(throwRef.get());
|
||||
if(throwRef.get() != null) {
|
||||
throw new RuntimeException(throwRef.get());
|
||||
}
|
||||
|
||||
Assert.assertFalse(conn.isOpen());
|
||||
Assert.assertEquals(0, localServer.getAcceptedConnectionCount());
|
||||
|
@ -516,8 +517,9 @@ public class TestConnectionManagement extends LocalServerTestBase {
|
|||
}
|
||||
|
||||
abortingThread.join(5000);
|
||||
if(throwRef.get() != null)
|
||||
throw new RuntimeException(throwRef.get());
|
||||
if(throwRef.get() != null) {
|
||||
throw new RuntimeException(throwRef.get());
|
||||
}
|
||||
|
||||
Assert.assertFalse(conn.isOpen());
|
||||
Assert.assertEquals(0, localServer.getAcceptedConnectionCount());
|
||||
|
@ -570,15 +572,17 @@ public class TestConnectionManagement extends LocalServerTestBase {
|
|||
}
|
||||
|
||||
abortingThread.join(5000);
|
||||
if(throwRef.get() != null)
|
||||
throw new RuntimeException(throwRef.get());
|
||||
if(throwRef.get() != null) {
|
||||
throw new RuntimeException(throwRef.get());
|
||||
}
|
||||
|
||||
Assert.assertFalse(conn.isOpen());
|
||||
// Give the server a bit of time to accept the connection, but
|
||||
// ensure that it can accept it.
|
||||
for(int i = 0; i < 10; i++) {
|
||||
if(localServer.getAcceptedConnectionCount() == 1)
|
||||
break;
|
||||
if(localServer.getAcceptedConnectionCount() == 1) {
|
||||
break;
|
||||
}
|
||||
Thread.sleep(100);
|
||||
}
|
||||
Assert.assertEquals(1, localServer.getAcceptedConnectionCount());
|
||||
|
@ -603,15 +607,17 @@ public class TestConnectionManagement extends LocalServerTestBase {
|
|||
}
|
||||
|
||||
void waitForState() throws InterruptedException {
|
||||
if(!waitLatch.await(1, TimeUnit.SECONDS))
|
||||
throw new RuntimeException("waited too long");
|
||||
if(!waitLatch.await(1, TimeUnit.SECONDS)) {
|
||||
throw new RuntimeException("waited too long");
|
||||
}
|
||||
}
|
||||
|
||||
void latch() {
|
||||
waitLatch.countDown();
|
||||
try {
|
||||
if (!continueLatch.await(60, TimeUnit.SECONDS))
|
||||
throw new RuntimeException("waited too long!");
|
||||
if (!continueLatch.await(60, TimeUnit.SECONDS)) {
|
||||
throw new RuntimeException("waited too long!");
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
@ -637,21 +643,24 @@ public class TestConnectionManagement extends LocalServerTestBase {
|
|||
final InetSocketAddress remoteAddress,
|
||||
final InetSocketAddress localAddress,
|
||||
final HttpContext context) throws IOException, ConnectTimeoutException {
|
||||
if(waitPolicy == WaitPolicy.BEFORE_CONNECT)
|
||||
latch();
|
||||
if(waitPolicy == WaitPolicy.BEFORE_CONNECT) {
|
||||
latch();
|
||||
}
|
||||
|
||||
Socket socket = delegate.connectSocket(
|
||||
connectTimeout, sock, host, remoteAddress, localAddress, context);
|
||||
|
||||
if(waitPolicy == WaitPolicy.AFTER_CONNECT)
|
||||
latch();
|
||||
if(waitPolicy == WaitPolicy.AFTER_CONNECT) {
|
||||
latch();
|
||||
}
|
||||
|
||||
return socket;
|
||||
}
|
||||
|
||||
public Socket createSocket(final HttpContext context) throws IOException {
|
||||
if(waitPolicy == WaitPolicy.BEFORE_CREATE)
|
||||
latch();
|
||||
if(waitPolicy == WaitPolicy.BEFORE_CREATE) {
|
||||
latch();
|
||||
}
|
||||
|
||||
return delegate.createSocket(context);
|
||||
}
|
||||
|
|
|
@ -82,8 +82,9 @@ public class EchoHandler
|
|||
}
|
||||
|
||||
HttpEntity entity = null;
|
||||
if (request instanceof HttpEntityEnclosingRequest)
|
||||
entity = ((HttpEntityEnclosingRequest)request).getEntity();
|
||||
if (request instanceof HttpEntityEnclosingRequest) {
|
||||
entity = ((HttpEntityEnclosingRequest)request).getEntity();
|
||||
}
|
||||
|
||||
// For some reason, just putting the incoming entity into
|
||||
// the response will not work. We have to buffer the message.
|
||||
|
|
|
@ -272,10 +272,11 @@ public class LocalTestServer {
|
|||
ServerSocket ssock = servicedSocket; // avoid synchronization
|
||||
StringBuilder sb = new StringBuilder(80);
|
||||
sb.append("LocalTestServer/");
|
||||
if (ssock == null)
|
||||
sb.append("stopped");
|
||||
else
|
||||
sb.append(ssock.getLocalSocketAddress());
|
||||
if (ssock == null) {
|
||||
sb.append("stopped");
|
||||
} else {
|
||||
sb.append(ssock.getLocalSocketAddress());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue