Fixed style check violations (tabs introduced by a previous commit)

git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@1433610 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Oleg Kalnichevski 2013-01-15 20:08:10 +00:00
parent 276a9c4597
commit 3d34035b17
65 changed files with 661 additions and 661 deletions

View File

@ -162,8 +162,8 @@ class BasicHttpCache implements HttpCache {
} }
Header hdr = resp.getFirstHeader(HTTP.CONTENT_LEN); Header hdr = resp.getFirstHeader(HTTP.CONTENT_LEN);
if (hdr == null) { if (hdr == null) {
return false; return false;
} }
int contentLength; int contentLength;
try { try {
contentLength = Integer.parseInt(hdr.getValue()); contentLength = Integer.parseInt(hdr.getValue());
@ -284,15 +284,15 @@ class BasicHttpCache implements HttpCache {
public HttpCacheEntry getCacheEntry(final HttpHost host, final HttpRequest request) throws IOException { public HttpCacheEntry getCacheEntry(final HttpHost host, final HttpRequest request) throws IOException {
HttpCacheEntry root = storage.getEntry(uriExtractor.getURI(host, request)); HttpCacheEntry root = storage.getEntry(uriExtractor.getURI(host, request));
if (root == null) { if (root == null) {
return null; return null;
} }
if (!root.hasVariants()) { if (!root.hasVariants()) {
return root; return root;
} }
String variantCacheKey = root.getVariantMap().get(uriExtractor.getVariantKey(request, root)); String variantCacheKey = root.getVariantMap().get(uriExtractor.getVariantKey(request, root));
if (variantCacheKey == null) { if (variantCacheKey == null) {
return null; return null;
} }
return storage.getEntry(variantCacheKey); return storage.getEntry(variantCacheKey);
} }
@ -306,8 +306,8 @@ class BasicHttpCache implements HttpCache {
Map<String,Variant> variants = new HashMap<String,Variant>(); Map<String,Variant> variants = new HashMap<String,Variant>();
HttpCacheEntry root = storage.getEntry(uriExtractor.getURI(host, request)); HttpCacheEntry root = storage.getEntry(uriExtractor.getURI(host, request));
if (root == null || !root.hasVariants()) { if (root == null || !root.hasVariants()) {
return variants; return variants;
} }
for(Map.Entry<String, String> variant : root.getVariantMap().entrySet()) { for(Map.Entry<String, String> variant : root.getVariantMap().entrySet()) {
String variantKey = variant.getKey(); String variantKey = variant.getKey();
String variantCacheKey = variant.getValue(); String variantCacheKey = variant.getValue();
@ -321,12 +321,12 @@ class BasicHttpCache implements HttpCache {
throws IOException { throws IOException {
HttpCacheEntry entry = storage.getEntry(variantCacheKey); HttpCacheEntry entry = storage.getEntry(variantCacheKey);
if (entry == null) { if (entry == null) {
return; return;
} }
Header etagHeader = entry.getFirstHeader(HeaderConstants.ETAG); Header etagHeader = entry.getFirstHeader(HeaderConstants.ETAG);
if (etagHeader == null) { if (etagHeader == null) {
return; return;
} }
variants.put(etagHeader.getValue(), new Variant(variantKey, variantCacheKey, entry)); variants.put(etagHeader.getValue(), new Variant(variantKey, variantCacheKey, entry));
} }

View File

@ -135,8 +135,8 @@ class CacheInvalidator {
protected void flushUriIfSameHost(final URL requestURL, final URL targetURL) { protected void flushUriIfSameHost(final URL requestURL, final URL targetURL) {
URL canonicalTarget = getAbsoluteURL(cacheKeyGenerator.canonicalizeUri(targetURL.toString())); URL canonicalTarget = getAbsoluteURL(cacheKeyGenerator.canonicalizeUri(targetURL.toString()));
if (canonicalTarget == null) { if (canonicalTarget == null) {
return; return;
} }
if (canonicalTarget.getAuthority().equalsIgnoreCase(requestURL.getAuthority())) { if (canonicalTarget.getAuthority().equalsIgnoreCase(requestURL.getAuthority())) {
flushEntry(canonicalTarget.toString()); flushEntry(canonicalTarget.toString());
} }
@ -145,8 +145,8 @@ class CacheInvalidator {
protected void flushRelativeUriFromSameHost(final URL reqURL, final String relUri) { protected void flushRelativeUriFromSameHost(final URL reqURL, final String relUri) {
URL relURL = getRelativeURL(reqURL, relUri); URL relURL = getRelativeURL(reqURL, relUri);
if (relURL == null) { if (relURL == null) {
return; return;
} }
flushUriIfSameHost(reqURL, relURL); flushUriIfSameHost(reqURL, relURL);
} }
@ -154,8 +154,8 @@ class CacheInvalidator {
protected boolean flushAbsoluteUriFromSameHost(final URL reqURL, final String uri) { protected boolean flushAbsoluteUriFromSameHost(final URL reqURL, final String uri) {
URL absURL = getAbsoluteURL(uri); URL absURL = getAbsoluteURL(uri);
if (absURL == null) { if (absURL == null) {
return false; return false;
} }
flushUriIfSameHost(reqURL,absURL); flushUriIfSameHost(reqURL,absURL);
return true; return true;
} }
@ -197,31 +197,31 @@ class CacheInvalidator {
final HttpRequest request, final HttpResponse response) { final HttpRequest request, final HttpResponse response) {
int status = response.getStatusLine().getStatusCode(); int status = response.getStatusLine().getStatusCode();
if (status < 200 || status > 299) { if (status < 200 || status > 299) {
return; return;
} }
URL reqURL = getAbsoluteURL(cacheKeyGenerator.getURI(host, request)); URL reqURL = getAbsoluteURL(cacheKeyGenerator.getURI(host, request));
if (reqURL == null) { if (reqURL == null) {
return; return;
} }
URL canonURL = getContentLocationURL(reqURL, response); URL canonURL = getContentLocationURL(reqURL, response);
if (canonURL == null) { if (canonURL == null) {
return; return;
} }
String cacheKey = cacheKeyGenerator.canonicalizeUri(canonURL.toString()); String cacheKey = cacheKeyGenerator.canonicalizeUri(canonURL.toString());
HttpCacheEntry entry = getEntry(cacheKey); HttpCacheEntry entry = getEntry(cacheKey);
if (entry == null) { if (entry == null) {
return; return;
} }
// do not invalidate if response is strictly older than entry // do not invalidate if response is strictly older than entry
// or if the etags match // or if the etags match
if (responseDateOlderThanEntryDate(response, entry)) { if (responseDateOlderThanEntryDate(response, entry)) {
return; return;
} }
if (!responseAndEntryEtagsDiffer(response, entry)) { if (!responseAndEntryEtagsDiffer(response, entry)) {
return; return;
} }
flushUriIfSameHost(reqURL, canonURL); flushUriIfSameHost(reqURL, canonURL);
} }
@ -229,13 +229,13 @@ class CacheInvalidator {
private URL getContentLocationURL(final URL reqURL, final HttpResponse response) { private URL getContentLocationURL(final URL reqURL, final HttpResponse response) {
Header clHeader = response.getFirstHeader("Content-Location"); Header clHeader = response.getFirstHeader("Content-Location");
if (clHeader == null) { if (clHeader == null) {
return null; return null;
} }
String contentLocation = clHeader.getValue(); String contentLocation = clHeader.getValue();
URL canonURL = getAbsoluteURL(contentLocation); URL canonURL = getAbsoluteURL(contentLocation);
if (canonURL != null) { if (canonURL != null) {
return canonURL; return canonURL;
} }
return getRelativeURL(reqURL, contentLocation); return getRelativeURL(reqURL, contentLocation);
} }
@ -244,8 +244,8 @@ class CacheInvalidator {
Header entryEtag = entry.getFirstHeader(HeaderConstants.ETAG); Header entryEtag = entry.getFirstHeader(HeaderConstants.ETAG);
Header responseEtag = response.getFirstHeader(HeaderConstants.ETAG); Header responseEtag = response.getFirstHeader(HeaderConstants.ETAG);
if (entryEtag == null || responseEtag == null) { if (entryEtag == null || responseEtag == null) {
return false; return false;
} }
return (!entryEtag.getValue().equals(responseEtag.getValue())); return (!entryEtag.getValue().equals(responseEtag.getValue()));
} }

View File

@ -75,8 +75,8 @@ class CacheKeyGenerator {
int port = canonicalizePort(u.getPort(), protocol); int port = canonicalizePort(u.getPort(), protocol);
String path = canonicalizePath(u.getPath()); String path = canonicalizePath(u.getPath());
if ("".equals(path)) { if ("".equals(path)) {
path = "/"; path = "/";
} }
String query = u.getQuery(); String query = u.getQuery();
String file = (query != null) ? (path + "?" + query) : path; String file = (query != null) ? (path + "?" + query) : path;
URL out = new URL(protocol, hostname, port, file); URL out = new URL(protocol, hostname, port, file);
@ -112,8 +112,8 @@ class CacheKeyGenerator {
protected String getFullHeaderValue(final Header[] headers) { protected String getFullHeaderValue(final Header[] headers) {
if (headers == null) { if (headers == null) {
return ""; return "";
} }
StringBuilder buf = new StringBuilder(""); StringBuilder buf = new StringBuilder("");
boolean first = true; boolean first = true;
@ -140,8 +140,8 @@ class CacheKeyGenerator {
*/ */
public String getVariantURI(final HttpHost host, final HttpRequest req, final HttpCacheEntry entry) { public String getVariantURI(final HttpHost host, final HttpRequest req, final HttpCacheEntry entry) {
if (!entry.hasVariants()) { if (!entry.hasVariants()) {
return getURI(host, req); return getURI(host, req);
} }
return getVariantKey(req, entry) + getURI(host, req); return getVariantKey(req, entry) + getURI(host, req);
} }

View File

@ -57,18 +57,18 @@ class CacheValidityPolicy {
public long getFreshnessLifetimeSecs(final HttpCacheEntry entry) { public long getFreshnessLifetimeSecs(final HttpCacheEntry entry) {
long maxage = getMaxAge(entry); long maxage = getMaxAge(entry);
if (maxage > -1) { if (maxage > -1) {
return maxage; return maxage;
} }
Date dateValue = getDateValue(entry); Date dateValue = getDateValue(entry);
if (dateValue == null) { if (dateValue == null) {
return 0L; return 0L;
} }
Date expiry = getExpirationDate(entry); Date expiry = getExpirationDate(entry);
if (expiry == null) { if (expiry == null) {
return 0; return 0;
} }
long diff = expiry.getTime() - dateValue.getTime(); long diff = expiry.getTime() - dateValue.getTime();
return (diff / 1000); return (diff / 1000);
} }
@ -103,8 +103,8 @@ class CacheValidityPolicy {
if (dateValue != null && lastModifiedValue != null) { if (dateValue != null && lastModifiedValue != null) {
long diff = dateValue.getTime() - lastModifiedValue.getTime(); long diff = dateValue.getTime() - lastModifiedValue.getTime();
if (diff < 0) { if (diff < 0) {
return 0; return 0;
} }
return (long)(coefficient * (diff / 1000)); return (long)(coefficient * (diff / 1000));
} }
@ -175,8 +175,8 @@ class CacheValidityPolicy {
protected Date getDateValue(final HttpCacheEntry entry) { protected Date getDateValue(final HttpCacheEntry entry) {
Header dateHdr = entry.getFirstHeader(HTTP.DATE_HEADER); Header dateHdr = entry.getFirstHeader(HTTP.DATE_HEADER);
if (dateHdr == null) { if (dateHdr == null) {
return null; return null;
} }
try { try {
return DateUtils.parseDate(dateHdr.getValue()); return DateUtils.parseDate(dateHdr.getValue());
} catch (DateParseException dpe) { } catch (DateParseException dpe) {
@ -188,8 +188,8 @@ class CacheValidityPolicy {
protected Date getLastModifiedValue(final HttpCacheEntry entry) { protected Date getLastModifiedValue(final HttpCacheEntry entry) {
Header dateHdr = entry.getFirstHeader(HeaderConstants.LAST_MODIFIED); Header dateHdr = entry.getFirstHeader(HeaderConstants.LAST_MODIFIED);
if (dateHdr == null) { if (dateHdr == null) {
return null; return null;
} }
try { try {
return DateUtils.parseDate(dateHdr.getValue()); return DateUtils.parseDate(dateHdr.getValue());
} catch (DateParseException dpe) { } catch (DateParseException dpe) {
@ -201,8 +201,8 @@ class CacheValidityPolicy {
protected long getContentLengthValue(final HttpCacheEntry entry) { protected long getContentLengthValue(final HttpCacheEntry entry) {
Header cl = entry.getFirstHeader(HTTP.CONTENT_LEN); Header cl = entry.getFirstHeader(HTTP.CONTENT_LEN);
if (cl == null) { if (cl == null) {
return -1; return -1;
} }
try { try {
return Long.parseLong(cl.getValue()); return Long.parseLong(cl.getValue());
@ -229,12 +229,12 @@ class CacheValidityPolicy {
protected long getApparentAgeSecs(final HttpCacheEntry entry) { protected long getApparentAgeSecs(final HttpCacheEntry entry) {
Date dateValue = getDateValue(entry); Date dateValue = getDateValue(entry);
if (dateValue == null) { if (dateValue == null) {
return MAX_AGE; return MAX_AGE;
} }
long diff = entry.getResponseDate().getTime() - dateValue.getTime(); long diff = entry.getResponseDate().getTime() - dateValue.getTime();
if (diff < 0L) { if (diff < 0L) {
return 0; return 0;
} }
return (diff / 1000); return (diff / 1000);
} }
@ -299,8 +299,8 @@ class CacheValidityPolicy {
protected Date getExpirationDate(final HttpCacheEntry entry) { protected Date getExpirationDate(final HttpCacheEntry entry) {
Header expiresHeader = entry.getFirstHeader(HeaderConstants.EXPIRES); Header expiresHeader = entry.getFirstHeader(HeaderConstants.EXPIRES);
if (expiresHeader == null) { if (expiresHeader == null) {
return null; return null;
} }
try { try {
return DateUtils.parseDate(expiresHeader.getValue()); return DateUtils.parseDate(expiresHeader.getValue());
} catch (DateParseException dpe) { } catch (DateParseException dpe) {
@ -325,8 +325,8 @@ class CacheValidityPolicy {
long age = getCurrentAgeSecs(entry, now); long age = getCurrentAgeSecs(entry, now);
long freshness = getFreshnessLifetimeSecs(entry); long freshness = getFreshnessLifetimeSecs(entry);
if (age <= freshness) { if (age <= freshness) {
return 0L; return 0L;
} }
return (age - freshness); return (age - freshness);
} }

View File

@ -152,8 +152,8 @@ class CachedHttpResponseGenerator {
private void addMissingContentLengthHeader(final HttpResponse response, final HttpEntity entity) { private void addMissingContentLengthHeader(final HttpResponse response, final HttpEntity entity) {
if (transferEncodingIsPresent(response)) { if (transferEncodingIsPresent(response)) {
return; return;
} }
Header contentLength = response.getFirstHeader(HTTP.CONTENT_LEN); Header contentLength = response.getFirstHeader(HTTP.CONTENT_LEN);
if (contentLength == null) { if (contentLength == null) {

View File

@ -74,29 +74,29 @@ class CachedResponseSuitabilityChecker {
private boolean isFreshEnough(final HttpCacheEntry entry, final HttpRequest request, final Date now) { private boolean isFreshEnough(final HttpCacheEntry entry, final HttpRequest request, final Date now) {
if (validityStrategy.isResponseFresh(entry, now)) { if (validityStrategy.isResponseFresh(entry, now)) {
return true; return true;
} }
if (useHeuristicCaching && if (useHeuristicCaching &&
validityStrategy.isResponseHeuristicallyFresh(entry, now, heuristicCoefficient, heuristicDefaultLifetime)) { validityStrategy.isResponseHeuristicallyFresh(entry, now, heuristicCoefficient, heuristicDefaultLifetime)) {
return true; return true;
} }
if (originInsistsOnFreshness(entry)) { if (originInsistsOnFreshness(entry)) {
return false; return false;
} }
long maxstale = getMaxStale(request); long maxstale = getMaxStale(request);
if (maxstale == -1) { if (maxstale == -1) {
return false; return false;
} }
return (maxstale > validityStrategy.getStalenessSecs(entry, now)); return (maxstale > validityStrategy.getStalenessSecs(entry, now));
} }
private boolean originInsistsOnFreshness(final HttpCacheEntry entry) { private boolean originInsistsOnFreshness(final HttpCacheEntry entry) {
if (validityStrategy.mustRevalidate(entry)) { if (validityStrategy.mustRevalidate(entry)) {
return true; return true;
} }
if (!sharedCache) { if (!sharedCache) {
return false; return false;
} }
return validityStrategy.proxyRevalidate(entry) || return validityStrategy.proxyRevalidate(entry) ||
validityStrategy.hasCacheControlDirective(entry, "s-maxage"); validityStrategy.hasCacheControlDirective(entry, "s-maxage");
} }
@ -113,8 +113,8 @@ class CachedResponseSuitabilityChecker {
try { try {
long val = Long.parseLong(elt.getValue()); long val = Long.parseLong(elt.getValue());
if (val < 0) { if (val < 0) {
val = 0; val = 0;
} }
if (maxstale == -1 || val < maxstale) { if (maxstale == -1 || val < maxstale) {
maxstale = val; maxstale = val;
} }
@ -212,8 +212,8 @@ class CachedResponseSuitabilityChecker {
try { try {
long minfresh = Long.parseLong(elt.getValue()); long minfresh = Long.parseLong(elt.getValue());
if (minfresh < 0L) { if (minfresh < 0L) {
return false; return false;
} }
long age = validityStrategy.getCurrentAgeSecs(entry, now); long age = validityStrategy.getCurrentAgeSecs(entry, now);
long freshness = validityStrategy.getFreshnessLifetimeSecs(entry); long freshness = validityStrategy.getFreshnessLifetimeSecs(entry);
if (freshness - age < minfresh) { if (freshness - age < minfresh) {

View File

@ -487,8 +487,8 @@ public class CachingExec implements ClientExecChain {
long age = validityPolicy.getCurrentAgeSecs(entry, now); long age = validityPolicy.getCurrentAgeSecs(entry, now);
long lifetime = validityPolicy.getFreshnessLifetimeSecs(entry); long lifetime = validityPolicy.getFreshnessLifetimeSecs(entry);
if (age - lifetime > maxstale) { if (age - lifetime > maxstale) {
return true; return true;
} }
} catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) {
return true; return true;
} }
@ -506,8 +506,8 @@ public class CachingExec implements ClientExecChain {
final ProtocolVersion pv = msg.getProtocolVersion(); final ProtocolVersion pv = msg.getProtocolVersion();
String existingEntry = viaHeaders.get(pv); String existingEntry = viaHeaders.get(pv);
if (existingEntry != null) { if (existingEntry != null) {
return existingEntry; return existingEntry;
} }
final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.http.client", getClass().getClassLoader()); final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.http.client", getClass().getClassLoader());
final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE; final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
@ -549,16 +549,16 @@ public class CachingExec implements ClientExecChain {
RequestLine line = request.getRequestLine(); RequestLine line = request.getRequestLine();
if (!HeaderConstants.OPTIONS_METHOD.equals(line.getMethod())) { if (!HeaderConstants.OPTIONS_METHOD.equals(line.getMethod())) {
return false; return false;
} }
if (!"*".equals(line.getUri())) { if (!"*".equals(line.getUri())) {
return false; return false;
} }
if (!"0".equals(request.getFirstHeader(HeaderConstants.MAX_FORWARDS).getValue())) { if (!"0".equals(request.getFirstHeader(HeaderConstants.MAX_FORWARDS).getValue())) {
return false; return false;
} }
return true; return true;
} }
@ -595,8 +595,8 @@ public class CachingExec implements ClientExecChain {
Date entryDate = DateUtils.parseDate(entryDateHeader.getValue()); Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
Date respDate = DateUtils.parseDate(responseDateHeader.getValue()); Date respDate = DateUtils.parseDate(responseDateHeader.getValue());
if (respDate.before(entryDate)) { if (respDate.before(entryDate)) {
return true; return true;
} }
} catch (DateParseException e) { } catch (DateParseException e) {
// either backend response or cached entry did not have a valid // either backend response or cached entry did not have a valid
// Date header, so we can't tell if they are out of order // Date header, so we can't tell if they are out of order
@ -853,16 +853,16 @@ public class CachingExec implements ClientExecChain {
// nop // nop
} }
if (existing == null) { if (existing == null) {
return false; return false;
} }
Header entryDateHeader = existing.getFirstHeader(HTTP.DATE_HEADER); Header entryDateHeader = existing.getFirstHeader(HTTP.DATE_HEADER);
if (entryDateHeader == null) { if (entryDateHeader == null) {
return false; return false;
} }
Header responseDateHeader = backendResponse.getFirstHeader(HTTP.DATE_HEADER); Header responseDateHeader = backendResponse.getFirstHeader(HTTP.DATE_HEADER);
if (responseDateHeader == null) { if (responseDateHeader == null) {
return false; return false;
} }
try { try {
Date entryDate = DateUtils.parseDate(entryDateHeader.getValue()); Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
Date responseDate = DateUtils.parseDate(responseDateHeader.getValue()); Date responseDate = DateUtils.parseDate(responseDateHeader.getValue());

View File

@ -433,8 +433,8 @@ public class CachingHttpClient implements HttpClient {
HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse( HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse(
request, context); request, context);
if (fatalErrorResponse != null) { if (fatalErrorResponse != null) {
return fatalErrorResponse; return fatalErrorResponse;
} }
requestCompliance.makeRequestCompliant(request); requestCompliance.makeRequestCompliant(request);
request.addHeader("Via",via); request.addHeader("Via",via);
@ -654,8 +654,8 @@ public class CachingHttpClient implements HttpClient {
long age = validityPolicy.getCurrentAgeSecs(entry, now); long age = validityPolicy.getCurrentAgeSecs(entry, now);
long lifetime = validityPolicy.getFreshnessLifetimeSecs(entry); long lifetime = validityPolicy.getFreshnessLifetimeSecs(entry);
if (age - lifetime > maxstale) { if (age - lifetime > maxstale) {
return true; return true;
} }
} catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) {
return true; return true;
} }
@ -673,8 +673,8 @@ public class CachingHttpClient implements HttpClient {
final ProtocolVersion pv = msg.getProtocolVersion(); final ProtocolVersion pv = msg.getProtocolVersion();
String existingEntry = viaHeaders.get(pv); String existingEntry = viaHeaders.get(pv);
if (existingEntry != null) { if (existingEntry != null) {
return existingEntry; return existingEntry;
} }
final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.http.client", getClass().getClassLoader()); final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.http.client", getClass().getClassLoader());
final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE; final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
@ -727,16 +727,16 @@ public class CachingHttpClient implements HttpClient {
RequestLine line = request.getRequestLine(); RequestLine line = request.getRequestLine();
if (!HeaderConstants.OPTIONS_METHOD.equals(line.getMethod())) { if (!HeaderConstants.OPTIONS_METHOD.equals(line.getMethod())) {
return false; return false;
} }
if (!"*".equals(line.getUri())) { if (!"*".equals(line.getUri())) {
return false; return false;
} }
if (!"0".equals(request.getFirstHeader(HeaderConstants.MAX_FORWARDS).getValue())) { if (!"0".equals(request.getFirstHeader(HeaderConstants.MAX_FORWARDS).getValue())) {
return false; return false;
} }
return true; return true;
} }
@ -763,8 +763,8 @@ public class CachingHttpClient implements HttpClient {
Date entryDate = DateUtils.parseDate(entryDateHeader.getValue()); Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
Date respDate = DateUtils.parseDate(responseDateHeader.getValue()); Date respDate = DateUtils.parseDate(responseDateHeader.getValue());
if (respDate.before(entryDate)) { if (respDate.before(entryDate)) {
return true; return true;
} }
} catch (DateParseException e) { } catch (DateParseException e) {
// either backend response or cached entry did not have a valid // either backend response or cached entry did not have a valid
// Date header, so we can't tell if they are out of order // Date header, so we can't tell if they are out of order
@ -910,8 +910,8 @@ public class CachingHttpClient implements HttpClient {
cachedResponse.addHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\""); cachedResponse.addHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\"");
HttpEntity errorBody = backendResponse.getEntity(); HttpEntity errorBody = backendResponse.getEntity();
if (errorBody != null) { if (errorBody != null) {
EntityUtils.consume(errorBody); EntityUtils.consume(errorBody);
} }
return cachedResponse; return cachedResponse;
} }
@ -985,16 +985,16 @@ public class CachingHttpClient implements HttpClient {
// nop // nop
} }
if (existing == null) { if (existing == null) {
return false; return false;
} }
Header entryDateHeader = existing.getFirstHeader(HTTP.DATE_HEADER); Header entryDateHeader = existing.getFirstHeader(HTTP.DATE_HEADER);
if (entryDateHeader == null) { if (entryDateHeader == null) {
return false; return false;
} }
Header responseDateHeader = backendResponse.getFirstHeader(HTTP.DATE_HEADER); Header responseDateHeader = backendResponse.getFirstHeader(HTTP.DATE_HEADER);
if (responseDateHeader == null) { if (responseDateHeader == null) {
return false; return false;
} }
try { try {
Date entryDate = DateUtils.parseDate(entryDateHeader.getValue()); Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
Date responseDate = DateUtils.parseDate(responseDateHeader.getValue()); Date responseDate = DateUtils.parseDate(responseDateHeader.getValue());

View File

@ -126,8 +126,8 @@ class RequestProtocolCompliance {
} }
} }
if (!shouldStrip) { if (!shouldStrip) {
return; return;
} }
request.removeHeaders(HeaderConstants.CACHE_CONTROL); request.removeHeaders(HeaderConstants.CACHE_CONTROL);
request.setHeader(HeaderConstants.CACHE_CONTROL, buildHeaderFromElements(outElts)); request.setHeader(HeaderConstants.CACHE_CONTROL, buildHeaderFromElements(outElts));
} }
@ -304,13 +304,13 @@ class RequestProtocolCompliance {
Header range = request.getFirstHeader(HeaderConstants.RANGE); Header range = request.getFirstHeader(HeaderConstants.RANGE);
if (range == null) { if (range == null) {
return null; return null;
} }
Header ifRange = request.getFirstHeader(HeaderConstants.IF_RANGE); Header ifRange = request.getFirstHeader(HeaderConstants.IF_RANGE);
if (ifRange == null) { if (ifRange == null) {
return null; return null;
} }
String val = ifRange.getValue(); String val = ifRange.getValue();
if (val.startsWith("W/")) { if (val.startsWith("W/")) {
@ -338,8 +338,8 @@ class RequestProtocolCompliance {
} else { } else {
Header ifNoneMatch = request.getFirstHeader(HeaderConstants.IF_NONE_MATCH); Header ifNoneMatch = request.getFirstHeader(HeaderConstants.IF_NONE_MATCH);
if (ifNoneMatch == null) { if (ifNoneMatch == null) {
return null; return null;
} }
String val2 = ifNoneMatch.getValue(); String val2 = ifNoneMatch.getValue();
if (val2.startsWith("W/")) { if (val2.startsWith("W/")) {

View File

@ -116,27 +116,27 @@ class ResponseCachingPolicy {
if (contentLength != null) { if (contentLength != null) {
int contentLengthValue = Integer.parseInt(contentLength.getValue()); int contentLengthValue = Integer.parseInt(contentLength.getValue());
if (contentLengthValue > this.maxObjectSizeBytes) { if (contentLengthValue > this.maxObjectSizeBytes) {
return false; return false;
} }
} }
Header[] ageHeaders = response.getHeaders(HeaderConstants.AGE); Header[] ageHeaders = response.getHeaders(HeaderConstants.AGE);
if (ageHeaders.length > 1) { if (ageHeaders.length > 1) {
return false; return false;
} }
Header[] expiresHeaders = response.getHeaders(HeaderConstants.EXPIRES); Header[] expiresHeaders = response.getHeaders(HeaderConstants.EXPIRES);
if (expiresHeaders.length > 1) { if (expiresHeaders.length > 1) {
return false; return false;
} }
Header[] dateHeaders = response.getHeaders(HTTP.DATE_HEADER); Header[] dateHeaders = response.getHeaders(HTTP.DATE_HEADER);
if (dateHeaders.length != 1) { if (dateHeaders.length != 1) {
return false; return false;
} }
try { try {
DateUtils.parseDate(dateHeaders[0].getValue()); DateUtils.parseDate(dateHeaders[0].getValue());
@ -153,28 +153,28 @@ class ResponseCachingPolicy {
} }
if (isExplicitlyNonCacheable(response)) { if (isExplicitlyNonCacheable(response)) {
return false; return false;
} }
return (cacheable || isExplicitlyCacheable(response)); return (cacheable || isExplicitlyCacheable(response));
} }
private boolean unknownStatusCode(final int status) { private boolean unknownStatusCode(final int status) {
if (status >= 100 && status <= 101) { if (status >= 100 && status <= 101) {
return false; return false;
} }
if (status >= 200 && status <= 206) { if (status >= 200 && status <= 206) {
return false; return false;
} }
if (status >= 300 && status <= 307) { if (status >= 300 && status <= 307) {
return false; return false;
} }
if (status >= 400 && status <= 417) { if (status >= 400 && status <= 417) {
return false; return false;
} }
if (status >= 500 && status <= 505) { if (status >= 500 && status <= 505) {
return false; return false;
} }
return true; return true;
} }
@ -208,8 +208,8 @@ class ResponseCachingPolicy {
protected boolean isExplicitlyCacheable(final HttpResponse response) { protected boolean isExplicitlyCacheable(final HttpResponse response) {
if (response.getFirstHeader(HeaderConstants.EXPIRES) != null) { if (response.getFirstHeader(HeaderConstants.EXPIRES) != null) {
return true; return true;
} }
String[] cacheableParams = { HeaderConstants.CACHE_CONTROL_MAX_AGE, "s-maxage", String[] cacheableParams = { HeaderConstants.CACHE_CONTROL_MAX_AGE, "s-maxage",
HeaderConstants.CACHE_CONTROL_MUST_REVALIDATE, HeaderConstants.CACHE_CONTROL_MUST_REVALIDATE,
HeaderConstants.CACHE_CONTROL_PROXY_REVALIDATE, HeaderConstants.CACHE_CONTROL_PROXY_REVALIDATE,
@ -268,13 +268,13 @@ class ResponseCachingPolicy {
private boolean expiresHeaderLessOrEqualToDateHeaderAndNoCacheControl( private boolean expiresHeaderLessOrEqualToDateHeaderAndNoCacheControl(
final HttpResponse response) { final HttpResponse response) {
if (response.getFirstHeader(HeaderConstants.CACHE_CONTROL) != null) { if (response.getFirstHeader(HeaderConstants.CACHE_CONTROL) != null) {
return false; return false;
} }
Header expiresHdr = response.getFirstHeader(HeaderConstants.EXPIRES); Header expiresHdr = response.getFirstHeader(HeaderConstants.EXPIRES);
Header dateHdr = response.getFirstHeader(HTTP.DATE_HEADER); Header dateHdr = response.getFirstHeader(HTTP.DATE_HEADER);
if (expiresHdr == null || dateHdr == null) { if (expiresHdr == null || dateHdr == null) {
return false; return false;
} }
try { try {
Date expires = DateUtils.parseDate(expiresHdr.getValue()); Date expires = DateUtils.parseDate(expiresHdr.getValue());
Date date = DateUtils.parseDate(dateHdr.getValue()); Date date = DateUtils.parseDate(dateHdr.getValue());

View File

@ -95,8 +95,8 @@ class ResponseProtocolCompliance {
private void consumeBody(final HttpResponse response) throws IOException { private void consumeBody(final HttpResponse response) throws IOException {
HttpEntity body = response.getEntity(); HttpEntity body = response.getEntity();
if (body != null) { if (body != null) {
EntityUtils.consume(body); EntityUtils.consume(body);
} }
} }
private void warningsWithNonMatchingWarnDatesAreRemoved( private void warningsWithNonMatchingWarnDatesAreRemoved(
@ -109,14 +109,14 @@ class ResponseProtocolCompliance {
} }
if (responseDate == null) { if (responseDate == null) {
return; return;
} }
Header[] warningHeaders = response.getHeaders(HeaderConstants.WARNING); Header[] warningHeaders = response.getHeaders(HeaderConstants.WARNING);
if (warningHeaders == null || warningHeaders.length == 0) { if (warningHeaders == null || warningHeaders.length == 0) {
return; return;
} }
List<Header> newWarningHeaders = new ArrayList<Header>(); List<Header> newWarningHeaders = new ArrayList<Header>();
boolean modified = false; boolean modified = false;
@ -141,8 +141,8 @@ class ResponseProtocolCompliance {
private void identityIsNotUsedInContentEncoding(final HttpResponse response) { private void identityIsNotUsedInContentEncoding(final HttpResponse response) {
Header[] hdrs = response.getHeaders(HTTP.CONTENT_ENCODING); Header[] hdrs = response.getHeaders(HTTP.CONTENT_ENCODING);
if (hdrs == null || hdrs.length == 0) { if (hdrs == null || hdrs.length == 0) {
return; return;
} }
List<Header> newHeaders = new ArrayList<Header>(); List<Header> newHeaders = new ArrayList<Header>();
boolean modified = false; boolean modified = false;
for (Header h : hdrs) { for (Header h : hdrs) {
@ -153,8 +153,8 @@ class ResponseProtocolCompliance {
modified = true; modified = true;
} else { } else {
if (!first) { if (!first) {
buf.append(","); buf.append(",");
} }
buf.append(elt.toString()); buf.append(elt.toString());
first = false; first = false;
} }
@ -165,8 +165,8 @@ class ResponseProtocolCompliance {
} }
} }
if (!modified) { if (!modified) {
return; return;
} }
response.removeHeaders(HTTP.CONTENT_ENCODING); response.removeHeaders(HTTP.CONTENT_ENCODING);
for (Header h : newHeaders) { for (Header h : newHeaders) {
response.addHeader(h); response.addHeader(h);
@ -184,8 +184,8 @@ class ResponseProtocolCompliance {
final HttpResponse response) throws IOException { final HttpResponse response) throws IOException {
if (request.getFirstHeader(HeaderConstants.RANGE) != null if (request.getFirstHeader(HeaderConstants.RANGE) != null
|| response.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT) { || response.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT) {
return; return;
} }
consumeBody(response); consumeBody(response);
throw new ClientProtocolException(UNEXPECTED_PARTIAL_CONTENT); throw new ClientProtocolException(UNEXPECTED_PARTIAL_CONTENT);
@ -234,8 +234,8 @@ class ResponseProtocolCompliance {
HttpRequest originalRequest = request.getOriginal(); HttpRequest originalRequest = request.getOriginal();
if (originalRequest instanceof HttpEntityEnclosingRequest) { if (originalRequest instanceof HttpEntityEnclosingRequest) {
if (((HttpEntityEnclosingRequest)originalRequest).expectContinue()) { if (((HttpEntityEnclosingRequest)originalRequest).expectContinue()) {
return; return;
} }
} }
consumeBody(response); consumeBody(response);
throw new ClientProtocolException(UNEXPECTED_100_CONTINUE); throw new ClientProtocolException(UNEXPECTED_100_CONTINUE);

View File

@ -81,8 +81,8 @@ class WarningValue {
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
final int nextComma = src.indexOf(',', offs); final int nextComma = src.indexOf(',', offs);
if (nextComma == -1) { if (nextComma == -1) {
break; break;
} }
offs = nextComma + 1; offs = nextComma + 1;
} }
} }
@ -152,12 +152,12 @@ class WarningValue {
*/ */
protected void consumeToken() { protected void consumeToken() {
if (!isTokenChar(src.charAt(offs))) { if (!isTokenChar(src.charAt(offs))) {
parseError(); parseError();
} }
while(offs < src.length()) { while(offs < src.length()) {
if (!isTokenChar(src.charAt(offs))) { if (!isTokenChar(src.charAt(offs))) {
break; break;
} }
offs++; offs++;
} }
} }
@ -178,11 +178,11 @@ class WarningValue {
protected void consumeHostPort() { protected void consumeHostPort() {
Matcher m = HOSTPORT_PATTERN.matcher(src.substring(offs)); Matcher m = HOSTPORT_PATTERN.matcher(src.substring(offs));
if (!m.find()) { if (!m.find()) {
parseError(); parseError();
} }
if (m.start() != 0) { if (m.start() != 0) {
parseError(); parseError();
} }
offs += m.end(); offs += m.end();
} }
@ -212,8 +212,8 @@ class WarningValue {
*/ */
protected void consumeQuotedString() { protected void consumeQuotedString() {
if (src.charAt(offs) != '\"') { if (src.charAt(offs) != '\"') {
parseError(); parseError();
} }
offs++; offs++;
boolean foundEnd = false; boolean foundEnd = false;
while(offs < src.length() && !foundEnd) { while(offs < src.length() && !foundEnd) {
@ -231,8 +231,8 @@ class WarningValue {
} }
} }
if (!foundEnd) { if (!foundEnd) {
parseError(); parseError();
} }
} }
/* /*
@ -265,8 +265,8 @@ class WarningValue {
int curr = offs; int curr = offs;
Matcher m = WARN_DATE_PATTERN.matcher(src.substring(offs)); Matcher m = WARN_DATE_PATTERN.matcher(src.substring(offs));
if (!m.lookingAt()) { if (!m.lookingAt()) {
parseError(); parseError();
} }
offs += m.end(); offs += m.end();
try { try {
warnDate = DateUtils.parseDate(src.substring(curr+1,offs-1)); warnDate = DateUtils.parseDate(src.substring(curr+1,offs-1));

View File

@ -162,8 +162,8 @@ public class MemcachedHttpCacheStorage implements HttpCacheStorage {
byte[] bytes = serializeEntry(url, entry); byte[] bytes = serializeEntry(url, entry);
String key = getCacheKey(url); String key = getCacheKey(url);
if (key == null) { if (key == null) {
return; return;
} }
try { try {
client.set(key, 0, bytes); client.set(key, 0, bytes);
} catch (OperationTimeoutException ex) { } catch (OperationTimeoutException ex) {
@ -192,8 +192,8 @@ public class MemcachedHttpCacheStorage implements HttpCacheStorage {
private byte[] convertToByteArray(final Object o) { private byte[] convertToByteArray(final Object o) {
if (o == null) { if (o == null) {
return null; return null;
} }
if (!(o instanceof byte[])) { if (!(o instanceof byte[])) {
log.warn("got a non-bytearray back from memcached: " + o); log.warn("got a non-bytearray back from memcached: " + o);
return null; return null;
@ -204,8 +204,8 @@ public class MemcachedHttpCacheStorage implements HttpCacheStorage {
private MemcachedCacheEntry reconstituteEntry(final Object o) throws IOException { private MemcachedCacheEntry reconstituteEntry(final Object o) throws IOException {
byte[] bytes = convertToByteArray(o); byte[] bytes = convertToByteArray(o);
if (bytes == null) { if (bytes == null) {
return null; return null;
} }
MemcachedCacheEntry mce = memcachedCacheEntryFactory.getUnsetCacheEntry(); MemcachedCacheEntry mce = memcachedCacheEntryFactory.getUnsetCacheEntry();
try { try {
mce.set(bytes); mce.set(bytes);
@ -218,13 +218,13 @@ public class MemcachedHttpCacheStorage implements HttpCacheStorage {
public HttpCacheEntry getEntry(final String url) throws IOException { public HttpCacheEntry getEntry(final String url) throws IOException {
String key = getCacheKey(url); String key = getCacheKey(url);
if (key == null) { if (key == null) {
return null; return null;
} }
try { try {
MemcachedCacheEntry mce = reconstituteEntry(client.get(key)); MemcachedCacheEntry mce = reconstituteEntry(client.get(key));
if (mce == null || !url.equals(mce.getStorageKey())) { if (mce == null || !url.equals(mce.getStorageKey())) {
return null; return null;
} }
return mce.getHttpCacheEntry(); return mce.getHttpCacheEntry();
} catch (OperationTimeoutException ex) { } catch (OperationTimeoutException ex) {
throw new MemcachedOperationTimeoutException(ex); throw new MemcachedOperationTimeoutException(ex);
@ -234,8 +234,8 @@ public class MemcachedHttpCacheStorage implements HttpCacheStorage {
public void removeEntry(final String url) throws IOException { public void removeEntry(final String url) throws IOException {
String key = getCacheKey(url); String key = getCacheKey(url);
if (key == null) { if (key == null) {
return; return;
} }
try { try {
client.delete(key); client.delete(key);
} catch (OperationTimeoutException ex) { } catch (OperationTimeoutException ex) {
@ -273,8 +273,8 @@ public class MemcachedHttpCacheStorage implements HttpCacheStorage {
if (casResult != CASResponse.OK) { if (casResult != CASResponse.OK) {
numRetries++; numRetries++;
} else { } else {
return; return;
} }
} }
} catch (OperationTimeoutException ex) { } catch (OperationTimeoutException ex) {
throw new MemcachedOperationTimeoutException(ex); throw new MemcachedOperationTimeoutException(ex);

View File

@ -97,8 +97,8 @@ public class HttpTestUtils {
public static boolean isHopByHopHeader(final String name) { public static boolean isHopByHopHeader(final String name) {
for (String s : HOP_BY_HOP_HEADERS) { for (String s : HOP_BY_HOP_HEADERS) {
if (s.equalsIgnoreCase(name)) { if (s.equalsIgnoreCase(name)) {
return true; return true;
} }
} }
return false; return false;
} }
@ -109,8 +109,8 @@ public class HttpTestUtils {
public static boolean isMultiHeader(final String name) { public static boolean isMultiHeader(final String name) {
for (String s : MULTI_HEADERS) { for (String s : MULTI_HEADERS) {
if (s.equalsIgnoreCase(name)) { if (s.equalsIgnoreCase(name)) {
return true; return true;
} }
} }
return false; return false;
} }
@ -121,8 +121,8 @@ public class HttpTestUtils {
public static boolean isSingleHeader(final String name) { public static boolean isSingleHeader(final String name) {
for (String s : SINGLE_HEADERS) { for (String s : SINGLE_HEADERS) {
if (s.equalsIgnoreCase(name)) { if (s.equalsIgnoreCase(name)) {
return true; return true;
} }
} }
return false; return false;
} }
@ -133,17 +133,17 @@ public class HttpTestUtils {
InputStream i1 = e1.getContent(); InputStream i1 = e1.getContent();
InputStream i2 = e2.getContent(); InputStream i2 = e2.getContent();
if (i1 == null && i2 == null) { if (i1 == null && i2 == null) {
return true; return true;
} }
if (i1 == null || i2 == null) if (i1 == null || i2 == null)
{ {
return false; // avoid possible NPEs below return false; // avoid possible NPEs below
} }
int b1 = -1; int b1 = -1;
while ((b1 = i1.read()) != -1) { while ((b1 = i1.read()) != -1) {
if (b1 != i2.read()) { if (b1 != i2.read()) {
return false; return false;
} }
} }
return (-1 == i2.read()); return (-1 == i2.read());
} }
@ -207,8 +207,8 @@ public class HttpTestUtils {
String r1val = getCanonicalHeaderValue(r1, h.getName()); String r1val = getCanonicalHeaderValue(r1, h.getName());
String r2val = getCanonicalHeaderValue(r2, h.getName()); String r2val = getCanonicalHeaderValue(r2, h.getName());
if (!r1val.equals(r2val)) { if (!r1val.equals(r2val)) {
return false; return false;
} }
} }
} }
return true; return true;
@ -227,12 +227,12 @@ public class HttpTestUtils {
throws Exception { throws Exception {
final boolean entitiesEquivalent = equivalent(r1.getEntity(), r2.getEntity()); final boolean entitiesEquivalent = equivalent(r1.getEntity(), r2.getEntity());
if (!entitiesEquivalent) { if (!entitiesEquivalent) {
return false; return false;
} }
final boolean statusLinesEquivalent = semanticallyTransparent(r1.getStatusLine(), r2.getStatusLine()); final boolean statusLinesEquivalent = semanticallyTransparent(r1.getStatusLine(), r2.getStatusLine());
if (!statusLinesEquivalent) { if (!statusLinesEquivalent) {
return false; return false;
} }
final boolean e2eHeadersEquivalentSubset = isEndToEndHeaderSubset( final boolean e2eHeadersEquivalentSubset = isEndToEndHeaderSubset(
r1, r2); r1, r2);
return e2eHeadersEquivalentSubset; return e2eHeadersEquivalentSubset;

View File

@ -39,8 +39,8 @@ public class RequestEquivalent implements IArgumentMatcher {
public boolean matches(final Object actual) { public boolean matches(final Object actual) {
if (!(actual instanceof HttpRequest)) { if (!(actual instanceof HttpRequest)) {
return false; return false;
} }
HttpRequest other = (HttpRequest) actual; HttpRequest other = (HttpRequest) actual;
return HttpTestUtils.equivalent(expected, other); return HttpTestUtils.equivalent(expected, other);
} }

View File

@ -1414,8 +1414,8 @@ public class TestCachingExec {
@Override @Override
public int read() throws IOException { public int read() throws IOException {
if (closed) { if (closed) {
throw new SocketException("Socket closed"); throw new SocketException("Socket closed");
} }
throw new SocketTimeoutException("Read timed out"); throw new SocketTimeoutException("Read timed out");
} }
}, 128)); }, 128));

View File

@ -103,35 +103,35 @@ public class TestHttpCacheEntrySerializers {
// dates are only stored with second precision, so scrub milliseconds // dates are only stored with second precision, so scrub milliseconds
if (!((one.getRequestDate().getTime() / 1000) == (two.getRequestDate() if (!((one.getRequestDate().getTime() / 1000) == (two.getRequestDate()
.getTime() / 1000))) { .getTime() / 1000))) {
return false; return false;
} }
if (!((one.getResponseDate().getTime() / 1000) == (two if (!((one.getResponseDate().getTime() / 1000) == (two
.getResponseDate().getTime() / 1000))) { .getResponseDate().getTime() / 1000))) {
return false; return false;
} }
if (!one.getProtocolVersion().equals(two.getProtocolVersion())) { if (!one.getProtocolVersion().equals(two.getProtocolVersion())) {
return false; return false;
} }
byte[] onesByteArray = resourceToBytes(one.getResource()); byte[] onesByteArray = resourceToBytes(one.getResource());
byte[] twosByteArray = resourceToBytes(two.getResource()); byte[] twosByteArray = resourceToBytes(two.getResource());
if (!Arrays.equals(onesByteArray,twosByteArray)) { if (!Arrays.equals(onesByteArray,twosByteArray)) {
return false; return false;
} }
Header[] oneHeaders = one.getAllHeaders(); Header[] oneHeaders = one.getAllHeaders();
Header[] twoHeaders = two.getAllHeaders(); Header[] twoHeaders = two.getAllHeaders();
if (!(oneHeaders.length == twoHeaders.length)) { if (!(oneHeaders.length == twoHeaders.length)) {
return false; return false;
} }
for (int i = 0; i < oneHeaders.length; i++) { for (int i = 0; i < oneHeaders.length; i++) {
if (!oneHeaders[i].getName().equals(twoHeaders[i].getName())) { if (!oneHeaders[i].getName().equals(twoHeaders[i].getName())) {
return false; return false;
} }
if (!oneHeaders[i].getValue().equals(twoHeaders[i].getValue())) { if (!oneHeaders[i].getValue().equals(twoHeaders[i].getValue())) {
return false; return false;
} }
} }
return true; return true;

View File

@ -1652,11 +1652,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest {
boolean found2 = false; boolean found2 = false;
while ((b = i.read()) != -1) { while ((b = i.read()) != -1) {
if (b == 1) { if (b == 1) {
found1 = true; found1 = true;
} }
if (b == 2) { if (b == 2) {
found2 = true; found2 = true;
} }
} }
i.close(); i.close();
Assert.assertFalse(found1 && found2); // mixture of content Assert.assertFalse(found1 && found2); // mixture of content
@ -1746,11 +1746,11 @@ public class TestProtocolRequirements extends AbstractProtocolTest {
boolean found2 = false; boolean found2 = false;
while ((b = i.read()) != -1) { while ((b = i.read()) != -1) {
if (b == 1) { if (b == 1) {
found1 = true; found1 = true;
} }
if (b == 2) { if (b == 2) {
found2 = true; found2 = true;
} }
} }
i.close(); i.close();
Assert.assertFalse(found1 && found2); // mixture of content Assert.assertFalse(found1 && found2); // mixture of content
@ -2614,8 +2614,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest {
boolean foundWarning = false; boolean foundWarning = false;
for (Header h : result.getHeaders("Warning")) { for (Header h : result.getHeaders("Warning")) {
if (h.getValue().split(" ")[0].equals("111")) { if (h.getValue().split(" ")[0].equals("111")) {
foundWarning = true; foundWarning = true;
} }
} }
Assert.assertTrue(foundWarning); Assert.assertTrue(foundWarning);
} else { } else {
@ -2692,15 +2692,15 @@ public class TestProtocolRequirements extends AbstractProtocolTest {
for (Header h : result1.getHeaders("Warning")) { for (Header h : result1.getHeaders("Warning")) {
for (HeaderElement elt : h.getElements()) { for (HeaderElement elt : h.getElements()) {
if (elt.getName().startsWith("1")) { if (elt.getName().startsWith("1")) {
found1xxWarning = true; found1xxWarning = true;
} }
} }
} }
for (Header h : result2.getHeaders("Warning")) { for (Header h : result2.getHeaders("Warning")) {
for (HeaderElement elt : h.getElements()) { for (HeaderElement elt : h.getElements()) {
if (elt.getName().startsWith("1")) { if (elt.getName().startsWith("1")) {
found1xxWarning = true; found1xxWarning = true;
} }
} }
} }
Assert.assertFalse(found1xxWarning); Assert.assertFalse(found1xxWarning);
@ -2765,8 +2765,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest {
for (HeaderElement elt : h.getElements()) { for (HeaderElement elt : h.getElements()) {
String[] parts = elt.getName().split(" "); String[] parts = elt.getName().split(" ");
if ("214".equals(parts[0])) { if ("214".equals(parts[0])) {
found214Warning = true; found214Warning = true;
} }
} }
} }
Assert.assertTrue(found214Warning); Assert.assertTrue(found214Warning);
@ -2776,8 +2776,8 @@ public class TestProtocolRequirements extends AbstractProtocolTest {
for (HeaderElement elt : h.getElements()) { for (HeaderElement elt : h.getElements()) {
String[] parts = elt.getName().split(" "); String[] parts = elt.getName().split(" ");
if ("214".equals(parts[0])) { if ("214".equals(parts[0])) {
found214Warning = true; found214Warning = true;
} }
} }
} }
Assert.assertTrue(found214Warning); Assert.assertTrue(found214Warning);
@ -3170,15 +3170,15 @@ public class TestProtocolRequirements extends AbstractProtocolTest {
for (Header h : validation.getHeaders("If-Match")) { for (Header h : validation.getHeaders("If-Match")) {
for (HeaderElement elt : h.getElements()) { for (HeaderElement elt : h.getElements()) {
if ("W/\"etag\"".equals(elt.getName())) { if ("W/\"etag\"".equals(elt.getName())) {
foundETag = true; foundETag = true;
} }
} }
} }
for (Header h : validation.getHeaders("If-None-Match")) { for (Header h : validation.getHeaders("If-None-Match")) {
for (HeaderElement elt : h.getElements()) { for (HeaderElement elt : h.getElements()) {
if ("W/\"etag\"".equals(elt.getName())) { if ("W/\"etag\"".equals(elt.getName())) {
foundETag = true; foundETag = true;
} }
} }
} }
Assert.assertTrue(foundETag); Assert.assertTrue(foundETag);
@ -6062,16 +6062,16 @@ public class TestProtocolRequirements extends AbstractProtocolTest {
final String nestedSuffix = "\\)([^\\p{Cntrl}()]|\\\\\\p{ASCII})*\\)$"; final String nestedSuffix = "\\)([^\\p{Cntrl}()]|\\\\\\p{ASCII})*\\)$";
if (Pattern.matches(leafComment,s)) { if (Pattern.matches(leafComment,s)) {
return true; return true;
} }
Matcher pref = Pattern.compile(nestedPrefix).matcher(s); Matcher pref = Pattern.compile(nestedPrefix).matcher(s);
Matcher suff = Pattern.compile(nestedSuffix).matcher(s); Matcher suff = Pattern.compile(nestedSuffix).matcher(s);
if (!pref.find()) { if (!pref.find()) {
return false; return false;
} }
if (!suff.find()) { if (!suff.find()) {
return false; return false;
} }
return isValidComment(s.substring(pref.end() - 1, suff.start() + 1)); return isValidComment(s.substring(pref.end() - 1, suff.start() + 1));
} }

View File

@ -487,8 +487,8 @@ public class TestMemcachedHttpCacheStorage extends TestCase {
HttpCacheUpdateCallback callback = new HttpCacheUpdateCallback() { HttpCacheUpdateCallback callback = new HttpCacheUpdateCallback() {
public HttpCacheEntry update(final HttpCacheEntry old) { public HttpCacheEntry update(final HttpCacheEntry old) {
if (old == existingValue) { if (old == existingValue) {
return updatedValue; return updatedValue;
} }
assertSame(existingValue2, old); assertSame(existingValue2, old);
return updatedValue2; return updatedValue2;
} }

View File

@ -65,8 +65,8 @@ public final class BasicUserPrincipal implements Principal, Serializable {
@Override @Override
public boolean equals(final Object o) { public boolean equals(final Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
if (o instanceof BasicUserPrincipal) { if (o instanceof BasicUserPrincipal) {
BasicUserPrincipal that = (BasicUserPrincipal) o; BasicUserPrincipal that = (BasicUserPrincipal) o;
if (LangUtils.equals(this.username, that.username)) { if (LangUtils.equals(this.username, that.username)) {

View File

@ -151,8 +151,8 @@ public class NTCredentials implements Credentials, Serializable {
@Override @Override
public boolean equals(final Object o) { public boolean equals(final Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
if (o instanceof NTCredentials) { if (o instanceof NTCredentials) {
NTCredentials that = (NTCredentials) o; NTCredentials that = (NTCredentials) o;
if (LangUtils.equals(this.principal, that.principal) if (LangUtils.equals(this.principal, that.principal)

View File

@ -93,8 +93,8 @@ public class NTUserPrincipal implements Principal, Serializable {
@Override @Override
public boolean equals(final Object o) { public boolean equals(final Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
if (o instanceof NTUserPrincipal) { if (o instanceof NTUserPrincipal) {
NTUserPrincipal that = (NTUserPrincipal) o; NTUserPrincipal that = (NTUserPrincipal) o;
if (LangUtils.equals(this.username, that.username) if (LangUtils.equals(this.username, that.username)

View File

@ -100,8 +100,8 @@ public class UsernamePasswordCredentials implements Credentials, Serializable {
@Override @Override
public boolean equals(final Object o) { public boolean equals(final Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
if (o instanceof UsernamePasswordCredentials) { if (o instanceof UsernamePasswordCredentials) {
UsernamePasswordCredentials that = (UsernamePasswordCredentials) o; UsernamePasswordCredentials that = (UsernamePasswordCredentials) o;
if (LangUtils.equals(this.principal, that.principal)) { if (LangUtils.equals(this.principal, that.principal)) {

View File

@ -49,10 +49,10 @@ public class Rfc3492Idn implements Idn {
private int adapt(int delta, final int numpoints, final boolean firsttime) { private int adapt(int delta, final int numpoints, final boolean firsttime) {
if (firsttime) { if (firsttime) {
delta = delta / damp; delta = delta / damp;
} else { } else {
delta = delta / 2; delta = delta / 2;
} }
delta = delta + (delta / numpoints); delta = delta + (delta / numpoints);
int k = 0; int k = 0;
while (delta > ((base - tmin) * tmax) / 2) { while (delta > ((base - tmin) * tmax) / 2) {
@ -64,14 +64,14 @@ public class Rfc3492Idn implements Idn {
private int digit(final char c) { private int digit(final char c) {
if ((c >= 'A') && (c <= 'Z')) { if ((c >= 'A') && (c <= 'Z')) {
return (c - 'A'); return (c - 'A');
} }
if ((c >= 'a') && (c <= 'z')) { if ((c >= 'a') && (c <= 'z')) {
return (c - 'a'); return (c - 'a');
} }
if ((c >= '0') && (c <= '9')) { if ((c >= '0') && (c <= '9')) {
return (c - '0') + 26; return (c - '0') + 26;
} }
throw new IllegalArgumentException("illegal digit: "+ c); throw new IllegalArgumentException("illegal digit: "+ c);
} }
@ -81,11 +81,11 @@ public class Rfc3492Idn implements Idn {
while (tok.hasMoreTokens()) { while (tok.hasMoreTokens()) {
String t = tok.nextToken(); String t = tok.nextToken();
if (unicode.length() > 0) { if (unicode.length() > 0) {
unicode.append('.'); unicode.append('.');
} }
if (t.startsWith(ACE_PREFIX)) { if (t.startsWith(ACE_PREFIX)) {
t = decode(t.substring(4)); t = decode(t.substring(4));
} }
unicode.append(t); unicode.append(t);
} }
return unicode.toString(); return unicode.toString();
@ -107,8 +107,8 @@ public class Rfc3492Idn implements Idn {
int w = 1; int w = 1;
for (int k = base;; k += base) { for (int k = base;; k += base) {
if (input.length() == 0) { if (input.length() == 0) {
break; break;
} }
char c = input.charAt(0); char c = input.charAt(0);
input = input.substring(1); input = input.substring(1);
int digit = digit(c); int digit = digit(c);
@ -122,8 +122,8 @@ public class Rfc3492Idn implements Idn {
t = k - bias; t = k - bias;
} }
if (digit < t) { if (digit < t) {
break; break;
} }
w = w * (base - t); // FIXME fail on overflow w = w * (base - t); // FIXME fail on overflow
} }
bias = adapt(i - oldi, output.length() + 1, (oldi == 0)); bias = adapt(i - oldi, output.length() + 1, (oldi == 0));

View File

@ -89,8 +89,8 @@ public class BasicManagedEntity extends HttpEntityWrapper
private void ensureConsumed() throws IOException { private void ensureConsumed() throws IOException {
if (managedConn == null) { if (managedConn == null) {
return; return;
} }
try { try {
if (attemptReuse) { if (attemptReuse) {

View File

@ -196,11 +196,11 @@ public class EofSensorInputStream extends InputStream implements ConnectionRelea
try { try {
boolean scws = true; // should close wrapped stream? boolean scws = true; // should close wrapped stream?
if (eofWatcher != null) { if (eofWatcher != null) {
scws = eofWatcher.eofDetected(wrappedStream); scws = eofWatcher.eofDetected(wrappedStream);
} }
if (scws) { if (scws) {
wrappedStream.close(); wrappedStream.close();
} }
} finally { } finally {
wrappedStream = null; wrappedStream = null;
} }
@ -224,11 +224,11 @@ public class EofSensorInputStream extends InputStream implements ConnectionRelea
try { try {
boolean scws = true; // should close wrapped stream? boolean scws = true; // should close wrapped stream?
if (eofWatcher != null) { if (eofWatcher != null) {
scws = eofWatcher.streamClosed(wrappedStream); scws = eofWatcher.streamClosed(wrappedStream);
} }
if (scws) { if (scws) {
wrappedStream.close(); wrappedStream.close();
} }
} finally { } finally {
wrappedStream = null; wrappedStream = null;
} }
@ -254,11 +254,11 @@ public class EofSensorInputStream extends InputStream implements ConnectionRelea
try { try {
boolean scws = true; // should close wrapped stream? boolean scws = true; // should close wrapped stream?
if (eofWatcher != null) { if (eofWatcher != null) {
scws = eofWatcher.streamAbort(wrappedStream); scws = eofWatcher.streamAbort(wrappedStream);
} }
if (scws) { if (scws) {
wrappedStream.close(); wrappedStream.close();
} }
} finally { } finally {
wrappedStream = null; wrappedStream = null;
} }

View File

@ -111,16 +111,16 @@ public final class MultihomePlainSocketFactory implements SocketFactory {
Args.notNull(params, "HTTP parameters"); Args.notNull(params, "HTTP parameters");
if (sock == null) { if (sock == null) {
sock = createSocket(); sock = createSocket();
} }
if ((localAddress != null) || (localPort > 0)) { if ((localAddress != null) || (localPort > 0)) {
// we need to bind explicitly // we need to bind explicitly
if (localPort < 0) if (localPort < 0)
{ {
localPort = 0; // indicates "any" localPort = 0; // indicates "any"
} }
InetSocketAddress isa = InetSocketAddress isa =
new InetSocketAddress(localAddress, localPort); new InetSocketAddress(localAddress, localPort);

View File

@ -56,12 +56,12 @@ public class BasicRouteDirector implements HttpRouteDirector {
int step = UNREACHABLE; int step = UNREACHABLE;
if ((fact == null) || (fact.getHopCount() < 1)) { if ((fact == null) || (fact.getHopCount() < 1)) {
step = firstStep(plan); step = firstStep(plan);
} else if (plan.getHopCount() > 1) { } else if (plan.getHopCount() > 1) {
step = proxiedStep(plan, fact); step = proxiedStep(plan, fact);
} else { } else {
step = directStep(plan, fact); step = directStep(plan, fact);
} }
return step; return step;
@ -94,29 +94,29 @@ public class BasicRouteDirector implements HttpRouteDirector {
protected int directStep(final RouteInfo plan, final RouteInfo fact) { protected int directStep(final RouteInfo plan, final RouteInfo fact) {
if (fact.getHopCount() > 1) { if (fact.getHopCount() > 1) {
return UNREACHABLE; return UNREACHABLE;
} }
if (!plan.getTargetHost().equals(fact.getTargetHost())) if (!plan.getTargetHost().equals(fact.getTargetHost()))
{ {
return UNREACHABLE; return UNREACHABLE;
// If the security is too low, we could now suggest to layer // If the security is too low, we could now suggest to layer
// a secure protocol on the direct connection. Layering on direct // a secure protocol on the direct connection. Layering on direct
// connections has not been supported in HttpClient 3.x, we don't // 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. // consider it here until there is a real-life use case for it.
} }
// Should we tolerate if security is better than planned? // Should we tolerate if security is better than planned?
// (plan.isSecure() && !fact.isSecure()) // (plan.isSecure() && !fact.isSecure())
if (plan.isSecure() != fact.isSecure()) { if (plan.isSecure() != fact.isSecure()) {
return UNREACHABLE; return UNREACHABLE;
} }
// Local address has to match only if the plan specifies one. // Local address has to match only if the plan specifies one.
if ((plan.getLocalAddress() != null) && if ((plan.getLocalAddress() != null) &&
!plan.getLocalAddress().equals(fact.getLocalAddress()) !plan.getLocalAddress().equals(fact.getLocalAddress())
) { ) {
return UNREACHABLE; return UNREACHABLE;
} }
return COMPLETE; return COMPLETE;
} }
@ -134,47 +134,47 @@ public class BasicRouteDirector implements HttpRouteDirector {
protected int proxiedStep(final RouteInfo plan, final RouteInfo fact) { protected int proxiedStep(final RouteInfo plan, final RouteInfo fact) {
if (fact.getHopCount() <= 1) { if (fact.getHopCount() <= 1) {
return UNREACHABLE; return UNREACHABLE;
} }
if (!plan.getTargetHost().equals(fact.getTargetHost())) { if (!plan.getTargetHost().equals(fact.getTargetHost())) {
return UNREACHABLE; return UNREACHABLE;
} }
final int phc = plan.getHopCount(); final int phc = plan.getHopCount();
final int fhc = fact.getHopCount(); final int fhc = fact.getHopCount();
if (phc < fhc) { if (phc < fhc) {
return UNREACHABLE; return UNREACHABLE;
} }
for (int i=0; i<fhc-1; i++) { for (int i=0; i<fhc-1; i++) {
if (!plan.getHopTarget(i).equals(fact.getHopTarget(i))) { if (!plan.getHopTarget(i).equals(fact.getHopTarget(i))) {
return UNREACHABLE; return UNREACHABLE;
} }
} }
// now we know that the target matches and proxies so far are the same // now we know that the target matches and proxies so far are the same
if (phc > fhc) 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 // proxy chain and target are the same, check tunnelling and layering
if ((fact.isTunnelled() && !plan.isTunnelled()) || if ((fact.isTunnelled() && !plan.isTunnelled()) ||
(fact.isLayered() && !plan.isLayered())) { (fact.isLayered() && !plan.isLayered())) {
return UNREACHABLE; return UNREACHABLE;
} }
if (plan.isTunnelled() && !fact.isTunnelled()) { if (plan.isTunnelled() && !fact.isTunnelled()) {
return TUNNEL_TARGET; return TUNNEL_TARGET;
} }
if (plan.isLayered() && !fact.isLayered()) { if (plan.isLayered() && !fact.isLayered()) {
return LAYER_PROTOCOL; return LAYER_PROTOCOL;
} }
// tunnel and layering are the same, remains to check the security // tunnel and layering are the same, remains to check the security
// Should we tolerate if security is better than planned? // Should we tolerate if security is better than planned?
// (plan.isSecure() && !fact.isSecure()) // (plan.isSecure() && !fact.isSecure())
if (plan.isSecure() != fact.isSecure()) { if (plan.isSecure() != fact.isSecure()) {
return UNREACHABLE; return UNREACHABLE;
} }
return COMPLETE; return COMPLETE;
} }

View File

@ -102,11 +102,11 @@ public final class HttpRoute implements RouteInfo, Cloneable {
} }
// tunnelled is already checked above, that is in line with the default // tunnelled is already checked above, that is in line with the default
if (tunnelled == null) { if (tunnelled == null) {
tunnelled = TunnelType.PLAIN; tunnelled = TunnelType.PLAIN;
} }
if (layered == null) { if (layered == null) {
layered = LayerType.PLAIN; layered = LayerType.PLAIN;
} }
this.targetHost = target; this.targetHost = target;
this.localAddress = local; this.localAddress = local;
@ -215,8 +215,8 @@ public final class HttpRoute implements RouteInfo, Cloneable {
*/ */
private static HttpHost[] toChain(final HttpHost proxy) { private static HttpHost[] toChain(final HttpHost proxy) {
if (proxy == null) { if (proxy == null) {
return EMPTY_HTTP_HOST_ARRAY; return EMPTY_HTTP_HOST_ARRAY;
} }
return new HttpHost[]{ proxy }; return new HttpHost[]{ proxy };
} }
@ -232,8 +232,8 @@ public final class HttpRoute implements RouteInfo, Cloneable {
*/ */
private static HttpHost[] toChain(final HttpHost[] proxies) { private static HttpHost[] toChain(final HttpHost[] proxies) {
if ((proxies == null) || (proxies.length < 1)) { if ((proxies == null) || (proxies.length < 1)) {
return EMPTY_HTTP_HOST_ARRAY; return EMPTY_HTTP_HOST_ARRAY;
} }
// copy the proxy chain, the traditional way // copy the proxy chain, the traditional way
HttpHost[] result = new HttpHost[proxies.length]; HttpHost[] result = new HttpHost[proxies.length];
System.arraycopy(proxies, 0, result, 0, proxies.length); System.arraycopy(proxies, 0, result, 0, proxies.length);
@ -267,10 +267,10 @@ public final class HttpRoute implements RouteInfo, Cloneable {
HttpHost result = null; HttpHost result = null;
if (hop < hopcount-1) { if (hop < hopcount-1) {
result = this.proxyChain[hop]; result = this.proxyChain[hop];
} else { } else {
result = this.targetHost; result = this.targetHost;
} }
return result; return result;
} }
@ -317,8 +317,8 @@ public final class HttpRoute implements RouteInfo, Cloneable {
@Override @Override
public final boolean equals(final Object obj) { public final boolean equals(final Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (obj instanceof HttpRoute) { if (obj instanceof HttpRoute) {
HttpRoute that = (HttpRoute) obj; HttpRoute that = (HttpRoute) obj;
return return
@ -369,14 +369,14 @@ public final class HttpRoute implements RouteInfo, Cloneable {
} }
cab.append('{'); cab.append('{');
if (this.tunnelled == TunnelType.TUNNELLED) { if (this.tunnelled == TunnelType.TUNNELLED) {
cab.append('t'); cab.append('t');
} }
if (this.layered == LayerType.LAYERED) { if (this.layered == LayerType.LAYERED) {
cab.append('l'); cab.append('l');
} }
if (this.secure) { if (this.secure) {
cab.append('s'); cab.append('s');
} }
cab.append("}->"); cab.append("}->");
for (HttpHost aProxyChain : this.proxyChain) { for (HttpHost aProxyChain : this.proxyChain) {
cab.append(aProxyChain); cab.append(aProxyChain);

View File

@ -197,10 +197,10 @@ public final class RouteTracker implements RouteInfo, Cloneable {
int hops = 0; int hops = 0;
if (this.connected) { if (this.connected) {
if (proxyChain == null) { if (proxyChain == null) {
hops = 1; hops = 1;
} else { } else {
hops = proxyChain.length + 1; hops = proxyChain.length + 1;
} }
} }
return hops; return hops;
} }
@ -211,10 +211,10 @@ public final class RouteTracker implements RouteInfo, Cloneable {
Args.check(hop < hopcount, "Hop index exceeds tracked route length"); Args.check(hop < hopcount, "Hop index exceeds tracked route length");
HttpHost result = null; HttpHost result = null;
if (hop < hopcount-1) { if (hop < hopcount-1) {
result = this.proxyChain[hop]; result = this.proxyChain[hop];
} else { } else {
result = this.targetHost; result = this.targetHost;
} }
return result; return result;
} }
@ -273,11 +273,11 @@ public final class RouteTracker implements RouteInfo, Cloneable {
@Override @Override
public final boolean equals(final Object o) { public final boolean equals(final Object o) {
if (o == this) { if (o == this) {
return true; return true;
} }
if (!(o instanceof RouteTracker)) { if (!(o instanceof RouteTracker)) {
return false; return false;
} }
RouteTracker that = (RouteTracker) o; RouteTracker that = (RouteTracker) o;
return return
@ -332,17 +332,17 @@ public final class RouteTracker implements RouteInfo, Cloneable {
} }
cab.append('{'); cab.append('{');
if (this.connected) { if (this.connected) {
cab.append('c'); cab.append('c');
} }
if (this.tunnelled == TunnelType.TUNNELLED) { if (this.tunnelled == TunnelType.TUNNELLED) {
cab.append('t'); cab.append('t');
} }
if (this.layered == LayerType.LAYERED) { if (this.layered == LayerType.LAYERED) {
cab.append('l'); cab.append('l');
} }
if (this.secure) { if (this.secure) {
cab.append('s'); cab.append('s');
} }
cab.append("}->"); cab.append("}->");
if (this.proxyChain != null) { if (this.proxyChain != null) {
for (HttpHost element : this.proxyChain) { for (HttpHost element : this.proxyChain) {

View File

@ -238,8 +238,8 @@ public final class Scheme {
@Override @Override
public final boolean equals(final Object obj) { public final boolean equals(final Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (obj instanceof Scheme) { if (obj instanceof Scheme) {
Scheme that = (Scheme) obj; Scheme that = (Scheme) obj;
return this.name.equals(that.name) return this.name.equals(that.name)

View File

@ -80,11 +80,11 @@ class SchemeSocketFactoryAdaptor implements SchemeSocketFactory {
@Override @Override
public boolean equals(final Object obj) { public boolean equals(final Object obj) {
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (obj instanceof SchemeSocketFactoryAdaptor) { if (obj instanceof SchemeSocketFactoryAdaptor) {
return this.factory.equals(((SchemeSocketFactoryAdaptor)obj).factory); return this.factory.equals(((SchemeSocketFactoryAdaptor)obj).factory);
} else { } else {

View File

@ -84,11 +84,11 @@ class SocketFactoryAdaptor implements SocketFactory {
@Override @Override
public boolean equals(final Object obj) { public boolean equals(final Object obj) {
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (obj instanceof SocketFactoryAdaptor) { if (obj instanceof SocketFactoryAdaptor) {
return this.factory.equals(((SocketFactoryAdaptor)obj).factory); return this.factory.equals(((SocketFactoryAdaptor)obj).factory);
} else { } else {

View File

@ -162,16 +162,16 @@ public abstract class GGSSchemeBase extends AuthSchemeBase {
state = State.FAILED; state = State.FAILED;
if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL
|| gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) { || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) {
throw new InvalidCredentialsException(gsse.getMessage(), gsse); throw new InvalidCredentialsException(gsse.getMessage(), gsse);
} }
if (gsse.getMajor() == GSSException.NO_CRED ) { if (gsse.getMajor() == GSSException.NO_CRED ) {
throw new InvalidCredentialsException(gsse.getMessage(), gsse); throw new InvalidCredentialsException(gsse.getMessage(), gsse);
} }
if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN
|| gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN
|| gsse.getMajor() == GSSException.OLD_TOKEN) { || gsse.getMajor() == GSSException.OLD_TOKEN) {
throw new AuthenticationException(gsse.getMessage(), gsse); throw new AuthenticationException(gsse.getMessage(), gsse);
} }
// other error // other error
throw new AuthenticationException(gsse.getMessage()); throw new AuthenticationException(gsse.getMessage());
} }

View File

@ -186,8 +186,8 @@ final class NTLMEngineImpl implements NTLMEngine {
private static String stripDotSuffix(final String value) { private static String stripDotSuffix(final String value) {
int index = value.indexOf("."); int index = value.indexOf(".");
if (index != -1) { if (index != -1) {
return value.substring(0, index); return value.substring(0, index);
} }
return value; return value;
} }
@ -203,16 +203,16 @@ final class NTLMEngineImpl implements NTLMEngine {
private static int readULong(final byte[] src, final int index) throws NTLMEngineException { private static int readULong(final byte[] src, final int index) throws NTLMEngineException {
if (src.length < index + 4) { if (src.length < index + 4) {
throw new NTLMEngineException("NTLM authentication - buffer too small for DWORD"); throw new NTLMEngineException("NTLM authentication - buffer too small for DWORD");
} }
return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8) return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8)
| ((src[index + 2] & 0xff) << 16) | ((src[index + 3] & 0xff) << 24); | ((src[index + 2] & 0xff) << 16) | ((src[index + 3] & 0xff) << 24);
} }
private static int readUShort(final byte[] src, final int index) throws NTLMEngineException { private static int readUShort(final byte[] src, final int index) throws NTLMEngineException {
if (src.length < index + 2) { if (src.length < index + 2) {
throw new NTLMEngineException("NTLM authentication - buffer too small for WORD"); throw new NTLMEngineException("NTLM authentication - buffer too small for WORD");
} }
return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8); return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8);
} }
@ -220,9 +220,9 @@ final class NTLMEngineImpl implements NTLMEngine {
int length = readUShort(src, index); int length = readUShort(src, index);
int offset = readULong(src, index + 4); int offset = readULong(src, index + 4);
if (src.length < offset + length) { if (src.length < offset + length) {
throw new NTLMEngineException( throw new NTLMEngineException(
"NTLM authentication - buffer too small for data item"); "NTLM authentication - buffer too small for data item");
} }
byte[] buffer = new byte[length]; byte[] buffer = new byte[length];
System.arraycopy(src, offset, buffer, 0, length); System.arraycopy(src, offset, buffer, 0, length);
return buffer; return buffer;
@ -304,8 +304,8 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getClientChallenge() public byte[] getClientChallenge()
throws NTLMEngineException { throws NTLMEngineException {
if (clientChallenge == null) { if (clientChallenge == null) {
clientChallenge = makeRandomChallenge(); clientChallenge = makeRandomChallenge();
} }
return clientChallenge; return clientChallenge;
} }
@ -313,8 +313,8 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getSecondaryKey() public byte[] getSecondaryKey()
throws NTLMEngineException { throws NTLMEngineException {
if (secondaryKey == null) { if (secondaryKey == null) {
secondaryKey = makeSecondaryKey(); secondaryKey = makeSecondaryKey();
} }
return secondaryKey; return secondaryKey;
} }
@ -322,8 +322,8 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getLMHash() public byte[] getLMHash()
throws NTLMEngineException { throws NTLMEngineException {
if (lmHash == null) { if (lmHash == null) {
lmHash = lmHash(password); lmHash = lmHash(password);
} }
return lmHash; return lmHash;
} }
@ -331,8 +331,8 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getLMResponse() public byte[] getLMResponse()
throws NTLMEngineException { throws NTLMEngineException {
if (lmResponse == null) { if (lmResponse == null) {
lmResponse = lmResponse(getLMHash(),challenge); lmResponse = lmResponse(getLMHash(),challenge);
} }
return lmResponse; return lmResponse;
} }
@ -340,8 +340,8 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getNTLMHash() public byte[] getNTLMHash()
throws NTLMEngineException { throws NTLMEngineException {
if (ntlmHash == null) { if (ntlmHash == null) {
ntlmHash = ntlmHash(password); ntlmHash = ntlmHash(password);
} }
return ntlmHash; return ntlmHash;
} }
@ -349,8 +349,8 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getNTLMResponse() public byte[] getNTLMResponse()
throws NTLMEngineException { throws NTLMEngineException {
if (ntlmResponse == null) { if (ntlmResponse == null) {
ntlmResponse = lmResponse(getNTLMHash(),challenge); ntlmResponse = lmResponse(getNTLMHash(),challenge);
} }
return ntlmResponse; return ntlmResponse;
} }
@ -358,8 +358,8 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getNTLMv2Hash() public byte[] getNTLMv2Hash()
throws NTLMEngineException { throws NTLMEngineException {
if (ntlmv2Hash == null) { if (ntlmv2Hash == null) {
ntlmv2Hash = ntlmv2Hash(target, user, password); ntlmv2Hash = ntlmv2Hash(target, user, password);
} }
return ntlmv2Hash; return ntlmv2Hash;
} }
@ -383,8 +383,8 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getNTLMv2Blob() public byte[] getNTLMv2Blob()
throws NTLMEngineException { throws NTLMEngineException {
if (ntlmv2Blob == null) { if (ntlmv2Blob == null) {
ntlmv2Blob = createBlob(getClientChallenge(), targetInformation, getTimestamp()); ntlmv2Blob = createBlob(getClientChallenge(), targetInformation, getTimestamp());
} }
return ntlmv2Blob; return ntlmv2Blob;
} }
@ -392,8 +392,8 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getNTLMv2Response() public byte[] getNTLMv2Response()
throws NTLMEngineException { throws NTLMEngineException {
if (ntlmv2Response == null) { if (ntlmv2Response == null) {
ntlmv2Response = lmv2Response(getNTLMv2Hash(),challenge,getNTLMv2Blob()); ntlmv2Response = lmv2Response(getNTLMv2Hash(),challenge,getNTLMv2Blob());
} }
return ntlmv2Response; return ntlmv2Response;
} }
@ -401,8 +401,8 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getLMv2Response() public byte[] getLMv2Response()
throws NTLMEngineException { throws NTLMEngineException {
if (lmv2Response == null) { if (lmv2Response == null) {
lmv2Response = lmv2Response(getNTLMv2Hash(),challenge,getClientChallenge()); lmv2Response = lmv2Response(getNTLMv2Hash(),challenge,getClientChallenge());
} }
return lmv2Response; return lmv2Response;
} }
@ -410,8 +410,8 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getNTLM2SessionResponse() public byte[] getNTLM2SessionResponse()
throws NTLMEngineException { throws NTLMEngineException {
if (ntlm2SessionResponse == null) { if (ntlm2SessionResponse == null) {
ntlm2SessionResponse = ntlm2SessionResponse(getNTLMHash(),challenge,getClientChallenge()); ntlm2SessionResponse = ntlm2SessionResponse(getNTLMHash(),challenge,getClientChallenge());
} }
return ntlm2SessionResponse; return ntlm2SessionResponse;
} }
@ -573,8 +573,8 @@ final class NTLMEngineImpl implements NTLMEngine {
return lmResponse(ntlmHash, sessionHash); return lmResponse(ntlmHash, sessionHash);
} catch (Exception e) { } catch (Exception e) {
if (e instanceof NTLMEngineException) { if (e instanceof NTLMEngineException) {
throw (NTLMEngineException) e; throw (NTLMEngineException) e;
} }
throw new NTLMEngineException(e.getMessage(), e); throw new NTLMEngineException(e.getMessage(), e);
} }
} }
@ -819,23 +819,23 @@ final class NTLMEngineImpl implements NTLMEngine {
DEFAULT_CHARSET)); DEFAULT_CHARSET));
// Look for NTLM message // Look for NTLM message
if (messageContents.length < SIGNATURE.length) { if (messageContents.length < SIGNATURE.length) {
throw new NTLMEngineException("NTLM message decoding error - packet too short"); throw new NTLMEngineException("NTLM message decoding error - packet too short");
} }
int i = 0; int i = 0;
while (i < SIGNATURE.length) { while (i < SIGNATURE.length) {
if (messageContents[i] != SIGNATURE[i]) { if (messageContents[i] != SIGNATURE[i]) {
throw new NTLMEngineException( throw new NTLMEngineException(
"NTLM message expected - instead got unrecognized bytes"); "NTLM message expected - instead got unrecognized bytes");
} }
i++; i++;
} }
// Check to be sure there's a type 2 message indicator next // Check to be sure there's a type 2 message indicator next
int type = readULong(SIGNATURE.length); int type = readULong(SIGNATURE.length);
if (type != expectedType) { if (type != expectedType) {
throw new NTLMEngineException("NTLM type " + Integer.toString(expectedType) throw new NTLMEngineException("NTLM type " + Integer.toString(expectedType)
+ " message expected - instead got type " + Integer.toString(type)); + " message expected - instead got type " + Integer.toString(type));
} }
currentOutputPosition = messageContents.length; currentOutputPosition = messageContents.length;
} }
@ -856,16 +856,16 @@ final class NTLMEngineImpl implements NTLMEngine {
/** Read a byte from a position within the message buffer */ /** Read a byte from a position within the message buffer */
protected byte readByte(final int position) throws NTLMEngineException { protected byte readByte(final int position) throws NTLMEngineException {
if (messageContents.length < position + 1) { if (messageContents.length < position + 1) {
throw new NTLMEngineException("NTLM: Message too short"); throw new NTLMEngineException("NTLM: Message too short");
} }
return messageContents[position]; return messageContents[position];
} }
/** Read a bunch of bytes from a position in the message buffer */ /** Read a bunch of bytes from a position in the message buffer */
protected void readBytes(final byte[] buffer, final int position) throws NTLMEngineException { protected void readBytes(final byte[] buffer, final int position) throws NTLMEngineException {
if (messageContents.length < position + buffer.length) { if (messageContents.length < position + buffer.length) {
throw new NTLMEngineException("NTLM: Message too short"); throw new NTLMEngineException("NTLM: Message too short");
} }
System.arraycopy(messageContents, position, buffer, 0, buffer.length); System.arraycopy(messageContents, position, buffer, 0, buffer.length);
} }
@ -1084,10 +1084,10 @@ final class NTLMEngineImpl implements NTLMEngine {
flags = readULong(20); flags = readULong(20);
if ((flags & FLAG_REQUEST_UNICODE_ENCODING) == 0) { if ((flags & FLAG_REQUEST_UNICODE_ENCODING) == 0) {
throw new NTLMEngineException( throw new NTLMEngineException(
"NTLM type 2 message has flags that make no sense: " "NTLM type 2 message has flags that make no sense: "
+ Integer.toString(flags)); + Integer.toString(flags));
} }
// Do the target! // Do the target!
target = null; target = null;
@ -1179,10 +1179,10 @@ final class NTLMEngineImpl implements NTLMEngine {
ntResp = gen.getNTLMv2Response(); ntResp = gen.getNTLMv2Response();
lmResp = gen.getLMv2Response(); lmResp = gen.getLMv2Response();
if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) { if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) {
userSessionKey = gen.getLanManagerSessionKey(); userSessionKey = gen.getLanManagerSessionKey();
} else { } else {
userSessionKey = gen.getNTLMv2UserSessionKey(); userSessionKey = gen.getNTLMv2UserSessionKey();
} }
} else { } else {
// NTLMv1 // NTLMv1
if ((type2Flags & FLAG_REQUEST_NTLM2_SESSION) != 0) { if ((type2Flags & FLAG_REQUEST_NTLM2_SESSION) != 0) {
@ -1190,23 +1190,23 @@ final class NTLMEngineImpl implements NTLMEngine {
ntResp = gen.getNTLM2SessionResponse(); ntResp = gen.getNTLM2SessionResponse();
lmResp = gen.getLM2SessionResponse(); lmResp = gen.getLM2SessionResponse();
if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) { if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) {
userSessionKey = gen.getLanManagerSessionKey(); userSessionKey = gen.getLanManagerSessionKey();
} }
else { else {
userSessionKey = gen.getNTLM2SessionResponseUserSessionKey(); userSessionKey = gen.getNTLM2SessionResponseUserSessionKey();
// All the other flags we send (signing, sealing, key // All the other flags we send (signing, sealing, key
// exchange) are supported, but they don't do anything // exchange) are supported, but they don't do anything
// at all in an // at all in an
// NTLM2 context! So we're done at this point. // NTLM2 context! So we're done at this point.
} }
} else { } else {
ntResp = gen.getNTLMResponse(); ntResp = gen.getNTLMResponse();
lmResp = gen.getLMResponse(); lmResp = gen.getLMResponse();
if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) { if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) {
userSessionKey = gen.getLanManagerSessionKey(); userSessionKey = gen.getLanManagerSessionKey();
} else { } else {
userSessionKey = gen.getNTLMUserSessionKey(); userSessionKey = gen.getNTLMUserSessionKey();
} }
} }
} }
} catch (NTLMEngineException e) { } catch (NTLMEngineException e) {
@ -1215,17 +1215,17 @@ final class NTLMEngineImpl implements NTLMEngine {
ntResp = new byte[0]; ntResp = new byte[0];
lmResp = gen.getLMResponse(); lmResp = gen.getLMResponse();
if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) { if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) {
userSessionKey = gen.getLanManagerSessionKey(); userSessionKey = gen.getLanManagerSessionKey();
} else { } else {
userSessionKey = gen.getLMUserSessionKey(); userSessionKey = gen.getLMUserSessionKey();
} }
} }
if ((type2Flags & FLAG_REQUEST_EXPLICIT_KEY_EXCH) != 0) { if ((type2Flags & FLAG_REQUEST_EXPLICIT_KEY_EXCH) != 0) {
sessionKey = RC4(gen.getSecondaryKey(), userSessionKey); sessionKey = RC4(gen.getSecondaryKey(), userSessionKey);
} else { } else {
sessionKey = null; sessionKey = null;
} }
try { try {
domainBytes = domain.toUpperCase(Locale.US).getBytes("UnicodeLittleUnmarked"); domainBytes = domain.toUpperCase(Locale.US).getBytes("UnicodeLittleUnmarked");
@ -1247,10 +1247,10 @@ final class NTLMEngineImpl implements NTLMEngine {
int userLen = userBytes.length; int userLen = userBytes.length;
int sessionKeyLen; int sessionKeyLen;
if (sessionKey != null) { if (sessionKey != null) {
sessionKeyLen = sessionKey.length; sessionKeyLen = sessionKey.length;
} else { } else {
sessionKeyLen = 0; sessionKeyLen = 0;
} }
// Calculate the layout within the packet // Calculate the layout within the packet
int lmRespOffset = 72; // allocate space for the version int lmRespOffset = 72; // allocate space for the version
@ -1349,8 +1349,8 @@ final class NTLMEngineImpl implements NTLMEngine {
addBytes(userBytes); addBytes(userBytes);
addBytes(hostBytes); addBytes(hostBytes);
if (sessionKey != null) { if (sessionKey != null) {
addBytes(sessionKey); addBytes(sessionKey);
} }
return super.getResponse(); return super.getResponse();
} }

View File

@ -88,8 +88,8 @@ public class AIMDBackoffManager implements BackoffManager {
Long lastUpdate = getLastUpdate(lastRouteBackoffs, route); Long lastUpdate = getLastUpdate(lastRouteBackoffs, route);
long now = clock.getCurrentTime(); long now = clock.getCurrentTime();
if (now - lastUpdate.longValue() < coolDown) { if (now - lastUpdate.longValue() < coolDown) {
return; return;
} }
connPerRoute.setMaxPerRoute(route, getBackedOffPoolSize(curr)); connPerRoute.setMaxPerRoute(route, getBackedOffPoolSize(curr));
lastRouteBackoffs.put(route, Long.valueOf(now)); lastRouteBackoffs.put(route, Long.valueOf(now));
} }
@ -97,8 +97,8 @@ public class AIMDBackoffManager implements BackoffManager {
private int getBackedOffPoolSize(final int curr) { private int getBackedOffPoolSize(final int curr) {
if (curr <= 1) { if (curr <= 1) {
return 1; return 1;
} }
return (int)(Math.floor(backoffFactor * curr)); return (int)(Math.floor(backoffFactor * curr));
} }
@ -110,8 +110,8 @@ public class AIMDBackoffManager implements BackoffManager {
Long lastBackoff = getLastUpdate(lastRouteBackoffs, route); Long lastBackoff = getLastUpdate(lastRouteBackoffs, route);
long now = clock.getCurrentTime(); long now = clock.getCurrentTime();
if (now - lastProbe.longValue() < coolDown || now - lastBackoff.longValue() < coolDown) { if (now - lastProbe.longValue() < coolDown || now - lastBackoff.longValue() < coolDown) {
return; return;
} }
connPerRoute.setMaxPerRoute(route, max); connPerRoute.setMaxPerRoute(route, max);
lastRouteProbes.put(route, Long.valueOf(now)); lastRouteProbes.put(route, Long.valueOf(now));
} }
@ -120,8 +120,8 @@ public class AIMDBackoffManager implements BackoffManager {
private Long getLastUpdate(final Map<HttpRoute,Long> updates, final HttpRoute route) { private Long getLastUpdate(final Map<HttpRoute,Long> updates, final HttpRoute route) {
Long lastUpdate = updates.get(route); Long lastUpdate = updates.get(route);
if (lastUpdate == null) { if (lastUpdate == null) {
lastUpdate = Long.valueOf(0L); lastUpdate = Long.valueOf(0L);
} }
return lastUpdate; return lastUpdate;
} }

View File

@ -841,11 +841,11 @@ public abstract class AbstractHttpClient extends CloseableHttpClient {
backoffManager.backOff(route); backoffManager.backOff(route);
} }
if (e instanceof HttpException) { if (e instanceof HttpException) {
throw (HttpException)e; throw (HttpException)e;
} }
if (e instanceof IOException) { if (e instanceof IOException) {
throw (IOException)e; throw (IOException)e;
} }
throw new UndeclaredThrowableException(e); throw new UndeclaredThrowableException(e);
} }
if (connectionBackoffStrategy.shouldBackoff(out)) { if (connectionBackoffStrategy.shouldBackoff(out)) {

View File

@ -148,8 +148,8 @@ public class DecompressingHttpClient implements HttpClient {
HttpContext context) throws IOException, ClientProtocolException { HttpContext context) throws IOException, ClientProtocolException {
try { try {
if (context == null) { if (context == null) {
context = new BasicHttpContext(); context = new BasicHttpContext();
} }
HttpRequest wrapped; HttpRequest wrapped;
if (request instanceof HttpEntityEnclosingRequest) { if (request instanceof HttpEntityEnclosingRequest) {
wrapped = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request); wrapped = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request);
@ -208,8 +208,8 @@ public class DecompressingHttpClient implements HttpClient {
} finally { } finally {
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
if (entity != null) { if (entity != null) {
EntityUtils.consume(entity); EntityUtils.consume(entity);
} }
} }
} }

View File

@ -563,8 +563,8 @@ public class DefaultRequestDirector implements RequestDirector {
!response.getEntity().isStreaming()) { !response.getEntity().isStreaming()) {
// connection not needed and (assumed to be) in re-usable state // connection not needed and (assumed to be) in re-usable state
if (reuse) { if (reuse) {
managedConn.markReusable(); managedConn.markReusable();
} }
releaseConnection(); releaseConnection();
} else { } else {
// install an auto-release entity // install an auto-release entity

View File

@ -159,20 +159,20 @@ public abstract class AbstractClientConnAdapter implements ManagedClientConnecti
public boolean isOpen() { public boolean isOpen() {
OperatedClientConnection conn = getWrappedConnection(); OperatedClientConnection conn = getWrappedConnection();
if (conn == null) { if (conn == null) {
return false; return false;
} }
return conn.isOpen(); return conn.isOpen();
} }
public boolean isStale() { public boolean isStale() {
if (isReleased()) { if (isReleased()) {
return true; return true;
} }
OperatedClientConnection conn = getWrappedConnection(); OperatedClientConnection conn = getWrappedConnection();
if (conn == null) { if (conn == null) {
return true; return true;
} }
return conn.isStale(); return conn.isStale();
} }
@ -277,8 +277,8 @@ public abstract class AbstractClientConnAdapter implements ManagedClientConnecti
OperatedClientConnection conn = getWrappedConnection(); OperatedClientConnection conn = getWrappedConnection();
assertValid(conn); assertValid(conn);
if (!isOpen()) { if (!isOpen()) {
return null; return null;
} }
return conn.getSocket(); return conn.getSocket();
} }
@ -286,8 +286,8 @@ public abstract class AbstractClientConnAdapter implements ManagedClientConnecti
OperatedClientConnection conn = getWrappedConnection(); OperatedClientConnection conn = getWrappedConnection();
assertValid(conn); assertValid(conn);
if (!isOpen()) { if (!isOpen()) {
return null; return null;
} }
SSLSession result = null; SSLSession result = null;
Socket sock = conn.getSocket(); Socket sock = conn.getSocket();

View File

@ -151,8 +151,8 @@ public abstract class AbstractPooledConnAdapter extends AbstractClientConnAdapte
public void close() throws IOException { public void close() throws IOException {
AbstractPoolEntry entry = getPoolEntry(); AbstractPoolEntry entry = getPoolEntry();
if (entry != null) { if (entry != null) {
entry.shutdownEntry(); entry.shutdownEntry();
} }
OperatedClientConnection conn = getWrappedConnection(); OperatedClientConnection conn = getWrappedConnection();
if (conn != null) { if (conn != null) {
@ -163,8 +163,8 @@ public abstract class AbstractPooledConnAdapter extends AbstractClientConnAdapte
public void shutdown() throws IOException { public void shutdown() throws IOException {
AbstractPoolEntry entry = getPoolEntry(); AbstractPoolEntry entry = getPoolEntry();
if (entry != null) { if (entry != null) {
entry.shutdownEntry(); entry.shutdownEntry();
} }
OperatedClientConnection conn = getWrappedConnection(); OperatedClientConnection conn = getWrappedConnection();
if (conn != null) { if (conn != null) {

View File

@ -157,8 +157,8 @@ public class DefaultClientConnection extends SocketHttpClientConnection
} }
Socket sock = this.socket; // copy volatile attribute Socket sock = this.socket; // copy volatile attribute
if (sock != null) { if (sock != null) {
sock.close(); sock.close();
} }
} catch (IOException ex) { } catch (IOException ex) {
log.debug("I/O error shutting down connection", ex); log.debug("I/O error shutting down connection", ex);
} }

View File

@ -89,8 +89,8 @@ public class DefaultHttpRoutePlanner implements HttpRoutePlanner {
HttpRoute route = HttpRoute route =
ConnRouteParams.getForcedRoute(request.getParams()); ConnRouteParams.getForcedRoute(request.getParams());
if (route != null) { if (route != null) {
return route; return route;
} }
// If we get here, there is no forced route. // If we get here, there is no forced route.
// So we need a target to compute a route. // So we need a target to compute a route.

View File

@ -125,8 +125,8 @@ public class ProxySelectorRoutePlanner implements HttpRoutePlanner {
HttpRoute route = HttpRoute route =
ConnRouteParams.getForcedRoute(request.getParams()); ConnRouteParams.getForcedRoute(request.getParams());
if (route != null) { if (route != null) {
return route; return route;
} }
// If we get here, there is no forced route. // If we get here, there is no forced route.
// So we need a target to compute a route. // So we need a target to compute a route.
@ -171,11 +171,11 @@ public class ProxySelectorRoutePlanner implements HttpRoutePlanner {
// the proxy selector can be 'unset', so we better deal with null here // the proxy selector can be 'unset', so we better deal with null here
ProxySelector psel = this.proxySelector; ProxySelector psel = this.proxySelector;
if (psel == null) { if (psel == null) {
psel = ProxySelector.getDefault(); psel = ProxySelector.getDefault();
} }
if (psel == null) { if (psel == null) {
return null; return null;
} }
URI targetURI = null; URI targetURI = null;
try { try {

View File

@ -244,8 +244,8 @@ public class SingleClientConnManager implements ClientConnectionManager {
} }
if (recreate) { if (recreate) {
uniquePoolEntry = new PoolEntry(); uniquePoolEntry = new PoolEntry();
} }
managedConn = new ConnAdapter(uniquePoolEntry, route); managedConn = new ConnAdapter(uniquePoolEntry, route);
@ -267,9 +267,9 @@ public class SingleClientConnManager implements ClientConnectionManager {
ConnAdapter sca = (ConnAdapter) conn; ConnAdapter sca = (ConnAdapter) conn;
synchronized (sca) { synchronized (sca) {
if (sca.poolEntry == null) if (sca.poolEntry == null)
{ {
return; // already released return; // already released
} }
ClientConnectionManager manager = sca.getManager(); ClientConnectionManager manager = sca.getManager();
Asserts.check(manager == this, "Connection not obtained from this manager"); Asserts.check(manager == this, "Connection not obtained from this manager");
try { try {
@ -289,19 +289,19 @@ public class SingleClientConnManager implements ClientConnectionManager {
} }
} catch (IOException iox) { } catch (IOException iox) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Exception shutting down released connection.", log.debug("Exception shutting down released connection.",
iox); iox);
} }
} finally { } finally {
sca.detach(); sca.detach();
synchronized (this) { synchronized (this) {
managedConn = null; managedConn = null;
lastReleaseTime = System.currentTimeMillis(); lastReleaseTime = System.currentTimeMillis();
if(validDuration > 0) { if(validDuration > 0) {
connectionExpiresTime = timeUnit.toMillis(validDuration) + lastReleaseTime; connectionExpiresTime = timeUnit.toMillis(validDuration) + lastReleaseTime;
} else { } else {
connectionExpiresTime = Long.MAX_VALUE; connectionExpiresTime = Long.MAX_VALUE;
} }
} }
} }
} }
@ -341,8 +341,8 @@ public class SingleClientConnManager implements ClientConnectionManager {
synchronized (this) { synchronized (this) {
try { try {
if (uniquePoolEntry != null) { if (uniquePoolEntry != null) {
uniquePoolEntry.shutdown(); uniquePoolEntry.shutdown();
} }
} catch (IOException iox) { } catch (IOException iox) {
// ignore // ignore
log.debug("Problem while shutting down manager.", iox); log.debug("Problem while shutting down manager.", iox);
@ -356,8 +356,8 @@ public class SingleClientConnManager implements ClientConnectionManager {
protected void revokeConnection() { protected void revokeConnection() {
ConnAdapter conn = managedConn; ConnAdapter conn = managedConn;
if (conn == null) { if (conn == null) {
return; return;
} }
conn.detach(); conn.detach();
synchronized (this) { synchronized (this) {
@ -389,8 +389,8 @@ public class SingleClientConnManager implements ClientConnectionManager {
protected void close() throws IOException { protected void close() throws IOException {
shutdownEntry(); shutdownEntry();
if (connection.isOpen()) { if (connection.isOpen()) {
connection.close(); connection.close();
} }
} }
/** /**
@ -399,8 +399,8 @@ public class SingleClientConnManager implements ClientConnectionManager {
protected void shutdown() throws IOException { protected void shutdown() throws IOException {
shutdownEntry(); shutdownEntry();
if (connection.isOpen()) { if (connection.isOpen()) {
connection.shutdown(); connection.shutdown();
} }
} }
} }

View File

@ -195,8 +195,8 @@ public abstract class AbstractConnPool {
try { try {
if (isShutDown) { if (isShutDown) {
return; return;
} }
// close all connections that are issued to an application // close all connections that are issued to an application
Iterator<BasicPoolEntry> iter = leasedConnections.iterator(); Iterator<BasicPoolEntry> iter = leasedConnections.iterator();

View File

@ -500,9 +500,9 @@ public class ConnPoolByRoute extends AbstractConnPool {
// If the free entry isn't valid anymore, get rid of it // If the free entry isn't valid anymore, get rid of it
// and loop to find another one that might be valid. // and loop to find another one that might be valid.
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Closing expired free connection" log.debug("Closing expired free connection"
+ " [" + rospl.getRoute() + "][" + state + "]"); + " [" + rospl.getRoute() + "][" + state + "]");
} }
closeConnection(entry); closeConnection(entry);
// We use dropEntry instead of deleteEntry because the entry // We use dropEntry instead of deleteEntry because the entry
// is no longer "free" (we just allocated it), and deleteEntry // is no longer "free" (we just allocated it), and deleteEntry

View File

@ -243,8 +243,8 @@ public class RouteSpecificPool {
final boolean found = freeEntries.remove(entry); final boolean found = freeEntries.remove(entry);
if (found) { if (found) {
numEntries--; numEntries--;
} }
return found; return found;
} }
@ -303,8 +303,8 @@ public class RouteSpecificPool {
*/ */
public void removeThread(final WaitingThread wt) { public void removeThread(final WaitingThread wt) {
if (wt == null) { if (wt == null) {
return; return;
} }
this.waitingThreads.remove(wt); this.waitingThreads.remove(wt);
} }

View File

@ -271,9 +271,9 @@ public class ThreadSafeClientConnManager implements ClientConnectionManager {
} }
} catch (IOException iox) { } catch (IOException iox) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Exception shutting down released connection.", log.debug("Exception shutting down released connection.",
iox); iox);
} }
} finally { } finally {
boolean reusable = hca.isMarkedReusable(); boolean reusable = hca.isMarkedReusable();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {

View File

@ -146,8 +146,8 @@ public class WaitingThread {
} }
if (aborted) { if (aborted) {
throw new InterruptedException("Operation interrupted"); throw new InterruptedException("Operation interrupted");
} }
this.waiter = Thread.currentThread(); this.waiter = Thread.currentThread();
@ -160,8 +160,8 @@ public class WaitingThread {
success = true; success = true;
} }
if (aborted) { if (aborted) {
throw new InterruptedException("Operation interrupted"); throw new InterruptedException("Operation interrupted");
} }
} finally { } finally {
this.waiter = null; this.waiter = null;
} }

View File

@ -48,8 +48,8 @@ public class WaitingThreadAborter {
aborted = true; aborted = true;
if (waitingThread != null) { if (waitingThread != null) {
waitingThread.interrupt(); waitingThread.interrupt();
} }
} }
@ -62,8 +62,8 @@ public class WaitingThreadAborter {
public void setWaitingThread(final WaitingThread waitingThread) { public void setWaitingThread(final WaitingThread waitingThread) {
this.waitingThread = waitingThread; this.waitingThread = waitingThread;
if (aborted) { if (aborted) {
waitingThread.interrupt(); waitingThread.interrupt();
} }
} }
} }

View File

@ -157,8 +157,8 @@ public final class DateUtils {
ParsePosition pos = new ParsePosition(0); ParsePosition pos = new ParsePosition(0);
Date result = dateParser.parse(dateValue, pos); Date result = dateParser.parse(dateValue, pos);
if (pos.getIndex() != 0) { if (pos.getIndex() != 0) {
return result; return result;
} }
} }
// we were unable to parse the date // we were unable to parse the date

View File

@ -80,8 +80,8 @@ public class PublicSuffixFilter implements CookieAttributeHandler {
*/ */
public boolean match(final Cookie cookie, final CookieOrigin origin) { public boolean match(final Cookie cookie, final CookieOrigin origin) {
if (isForPublicSuffix(cookie)) { if (isForPublicSuffix(cookie)) {
return false; return false;
} }
return wrapped.match(cookie, origin); return wrapped.match(cookie, origin);
} }
@ -96,34 +96,34 @@ public class PublicSuffixFilter implements CookieAttributeHandler {
private boolean isForPublicSuffix(final Cookie cookie) { private boolean isForPublicSuffix(final Cookie cookie) {
String domain = cookie.getDomain(); String domain = cookie.getDomain();
if (domain.startsWith(".")) { if (domain.startsWith(".")) {
domain = domain.substring(1); domain = domain.substring(1);
} }
domain = Punycode.toUnicode(domain); domain = Punycode.toUnicode(domain);
// An exception rule takes priority over any other matching rule. // An exception rule takes priority over any other matching rule.
if (this.exceptions != null) { if (this.exceptions != null) {
if (this.exceptions.contains(domain)) { if (this.exceptions.contains(domain)) {
return false; return false;
} }
} }
if (this.suffixes == null) { if (this.suffixes == null) {
return false; return false;
} }
do { do {
if (this.suffixes.contains(domain)) { if (this.suffixes.contains(domain)) {
return true; return true;
} }
// patterns // patterns
if (domain.startsWith("*.")) { if (domain.startsWith("*.")) {
domain = domain.substring(2); domain = domain.substring(2);
} }
int nextdot = domain.indexOf('.'); int nextdot = domain.indexOf('.');
if (nextdot == -1) { if (nextdot == -1) {
break; break;
} }
domain = "*" + domain.substring(nextdot); domain = "*" + domain.substring(nextdot);
} while (domain.length() > 0); } while (domain.length() > 0);

View File

@ -67,21 +67,21 @@ public class PublicSuffixListParser {
more = readLine(r, sb); more = readLine(r, sb);
String line = sb.toString(); String line = sb.toString();
if (line.length() == 0) { if (line.length() == 0) {
continue; continue;
} }
if (line.startsWith("//")) if (line.startsWith("//"))
{ {
continue; //entire lines can also be commented using // continue; //entire lines can also be commented using //
} }
if (line.startsWith(".")) if (line.startsWith("."))
{ {
line = line.substring(1); // A leading dot is optional 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 // An exclamation mark (!) at the start of a rule marks an exception to a previous wildcard rule
boolean isException = line.startsWith("!"); boolean isException = line.startsWith("!");
if (isException) { if (isException) {
line = line.substring(1); line = line.substring(1);
} }
if (isException) { if (isException) {
exceptions.add(line); exceptions.add(line);
@ -108,19 +108,19 @@ public class PublicSuffixListParser {
while ((b = r.read()) != -1) { while ((b = r.read()) != -1) {
char c = (char) b; char c = (char) b;
if (c == '\n') { if (c == '\n') {
break; break;
} }
// Each line is only read up to the first whitespace // Each line is only read up to the first whitespace
if (Character.isWhitespace(c)) { if (Character.isWhitespace(c)) {
hitWhitespace = true; hitWhitespace = true;
} }
if (!hitWhitespace) { if (!hitWhitespace) {
sb.append(c); sb.append(c);
} }
if (sb.length() > MAX_LINE_LEN) if (sb.length() > MAX_LINE_LEN)
{ {
throw new IOException("Line too long"); // prevent excess memory usage throw new IOException("Line too long"); // prevent excess memory usage
} }
} }
return (b != -1); return (b != -1);
} }

View File

@ -83,14 +83,14 @@ public class BackoffStrategyExec implements ClientExecChain {
this.backoffManager.backOff(route); this.backoffManager.backOff(route);
} }
if (ex instanceof RuntimeException) { if (ex instanceof RuntimeException) {
throw (RuntimeException) ex; throw (RuntimeException) ex;
} }
if (ex instanceof HttpException) { if (ex instanceof HttpException) {
throw (HttpException) ex; throw (HttpException) ex;
} }
if (ex instanceof IOException) { if (ex instanceof IOException) {
throw (IOException) ex; throw (IOException) ex;
} }
throw new UndeclaredThrowableException(ex); throw new UndeclaredThrowableException(ex);
} }
if (this.connectionBackoffStrategy.shouldBackoff(out)) { if (this.connectionBackoffStrategy.shouldBackoff(out)) {

View File

@ -138,12 +138,12 @@ public class TestScheme {
String name = names.get(0); String name = names.get(0);
if ("http".equals(name)) { if ("http".equals(name)) {
flaghttp = true; flaghttp = true;
} else if ("https".equals(name)) { } else if ("https".equals(name)) {
flaghttps = true; flaghttps = true;
} else { } else {
Assert.fail("unexpected name in iterator: " + name); Assert.fail("unexpected name in iterator: " + name);
} }
Assert.assertNotNull(schmreg.get(name)); Assert.assertNotNull(schmreg.get(name));
schmreg.unregister(name); schmreg.unregister(name);
@ -153,12 +153,12 @@ public class TestScheme {
if ("http".equals(name)) { if ("http".equals(name)) {
if (flaghttp) { if (flaghttp) {
Assert.fail("name 'http' found twice"); Assert.fail("name 'http' found twice");
} }
} else if ("https".equals(name)) { } else if ("https".equals(name)) {
if (flaghttps) { if (flaghttps) {
Assert.fail("name 'https' found twice"); Assert.fail("name 'https' found twice");
} }
} else { } else {
Assert.fail("unexpected name in iterator: " + name); Assert.fail("unexpected name in iterator: " + name);
} }

View File

@ -692,8 +692,8 @@ public class TestRouteTracker {
*/ */
public final static String checkToString(final RouteTracker rt) { public final static String checkToString(final RouteTracker rt) {
if (rt == null) { if (rt == null) {
return null; return null;
} }
final String rts = rt.toString(); final String rts = rt.toString();

View File

@ -48,8 +48,8 @@ public class TestNTLMEngineImpl {
/* Test suite helper */ /* Test suite helper */
static byte toNibble(final char c) { static byte toNibble(final char c) {
if (c >= 'a' && c <= 'f') { if (c >= 'a' && c <= 'f') {
return (byte) (c - 'a' + 0x0a); return (byte) (c - 'a' + 0x0a);
} }
return (byte) (c - '0'); return (byte) (c - '0');
} }
@ -73,14 +73,14 @@ public class TestNTLMEngineImpl {
byte[] answer = md4.getOutput(); byte[] answer = md4.getOutput();
byte[] correctAnswer = toBytes(hexOutput); byte[] correctAnswer = toBytes(hexOutput);
if (answer.length != correctAnswer.length) { if (answer.length != correctAnswer.length) {
throw new Exception("Answer length disagrees for MD4('" + input + "')"); throw new Exception("Answer length disagrees for MD4('" + input + "')");
} }
int i = 0; int i = 0;
while (i < answer.length) { while (i < answer.length) {
if (answer[i] != correctAnswer[i]) { if (answer[i] != correctAnswer[i]) {
throw new Exception("Answer value for MD4('" + input + "') disagrees at position " throw new Exception("Answer value for MD4('" + input + "') disagrees at position "
+ Integer.toString(i)); + Integer.toString(i));
} }
i++; i++;
} }
} }

View File

@ -160,11 +160,11 @@ public class TestAIMDBackoffManager {
public void coolDownPeriodIsConfigurable() { public void coolDownPeriodIsConfigurable() {
long cd = new Random().nextLong() / 2; long cd = new Random().nextLong() / 2;
if (cd < 0) { if (cd < 0) {
cd *= -1; cd *= -1;
} }
if (cd < 1) { if (cd < 1) {
cd++; cd++;
} }
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
impl.setCooldownMillis(cd); impl.setCooldownMillis(cd);
clock.setCurrentTime(now); clock.setCurrentTime(now);

View File

@ -156,11 +156,11 @@ public class TestDecompressingHttpClient {
for(Header h : captured.getHeaders("Accept-Encoding")) { for(Header h : captured.getHeaders("Accept-Encoding")) {
for(HeaderElement elt : h.getElements()) { for(HeaderElement elt : h.getElements()) {
if ("gzip".equals(elt.getName())) { if ("gzip".equals(elt.getName())) {
foundGzip = true; foundGzip = true;
} }
if ("deflate".equals(elt.getName())) { if ("deflate".equals(elt.getName())) {
foundDeflate = true; foundDeflate = true;
} }
} }
} }
assertTrue(foundGzip); assertTrue(foundGzip);

View File

@ -82,8 +82,8 @@ public class TestDefaultBackoffStrategy {
public void doesNotBackOffForNon503StatusCodes() { public void doesNotBackOffForNon503StatusCodes() {
for(int i = 100; i <= 599; i++) { for(int i = 100; i <= 599; i++) {
if (i == HttpStatus.SC_SERVICE_UNAVAILABLE) { if (i == HttpStatus.SC_SERVICE_UNAVAILABLE) {
continue; continue;
} }
HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1,
i, "Foo"); i, "Foo");
assertFalse(impl.shouldBackoff(resp)); assertFalse(impl.shouldBackoff(resp));

View File

@ -216,8 +216,8 @@ public class TestAbortHandling extends IntegrationTestBase {
try { try {
try { try {
if(!startLatch.await(1, TimeUnit.SECONDS)) { if(!startLatch.await(1, TimeUnit.SECONDS)) {
throw new RuntimeException("Took too long to start!"); throw new RuntimeException("Took too long to start!");
} }
} catch(InterruptedException interrupted) { } catch(InterruptedException interrupted) {
throw new RuntimeException("Never started!", interrupted); throw new RuntimeException("Never started!", interrupted);
} }
@ -376,12 +376,12 @@ public class TestAbortHandling extends IntegrationTestBase {
// zero usually means sleep forever, but CountDownLatch doesn't interpret it that way. // zero usually means sleep forever, but CountDownLatch doesn't interpret it that way.
if(timeout == 0) { if(timeout == 0) {
timeout = Integer.MAX_VALUE; timeout = Integer.MAX_VALUE;
} }
if(!awaitLatch.await(timeout, tunit)) { if(!awaitLatch.await(timeout, tunit)) {
throw new ConnectionPoolTimeoutException(); throw new ConnectionPoolTimeoutException();
} }
return Mockito.mock(HttpClientConnection.class); return Mockito.mock(HttpClientConnection.class);
} }
@ -436,12 +436,12 @@ public class TestAbortHandling extends IntegrationTestBase {
// zero usually means sleep forever, but CountDownLatch doesn't interpret it that way. // zero usually means sleep forever, but CountDownLatch doesn't interpret it that way.
if(timeout == 0) { if(timeout == 0) {
timeout = Integer.MAX_VALUE; timeout = Integer.MAX_VALUE;
} }
if(!awaitLatch.await(timeout, tunit)) { if(!awaitLatch.await(timeout, tunit)) {
throw new ConnectionPoolTimeoutException(); throw new ConnectionPoolTimeoutException();
} }
return Mockito.mock(HttpClientConnection.class); return Mockito.mock(HttpClientConnection.class);
} }
@ -491,8 +491,8 @@ public class TestAbortHandling extends IntegrationTestBase {
public void setCancellable(final Cancellable cancellable) { public void setCancellable(final Cancellable cancellable) {
try { try {
if(!releaseTriggerLatch.await(1, TimeUnit.SECONDS)) { if(!releaseTriggerLatch.await(1, TimeUnit.SECONDS)) {
throw new RuntimeException("Waited too long..."); throw new RuntimeException("Waited too long...");
} }
} catch(InterruptedException ie) { } catch(InterruptedException ie) {
throw new RuntimeException(ie); throw new RuntimeException(ie);
} }

View File

@ -463,8 +463,8 @@ public class TestConnectionManagement extends LocalServerTestBase {
abortingThread.join(5000); abortingThread.join(5000);
if(throwRef.get() != null) { if(throwRef.get() != null) {
throw new RuntimeException(throwRef.get()); throw new RuntimeException(throwRef.get());
} }
Assert.assertFalse(conn.isOpen()); Assert.assertFalse(conn.isOpen());
Assert.assertEquals(0, localServer.getAcceptedConnectionCount()); Assert.assertEquals(0, localServer.getAcceptedConnectionCount());
@ -518,8 +518,8 @@ public class TestConnectionManagement extends LocalServerTestBase {
abortingThread.join(5000); abortingThread.join(5000);
if(throwRef.get() != null) { if(throwRef.get() != null) {
throw new RuntimeException(throwRef.get()); throw new RuntimeException(throwRef.get());
} }
Assert.assertFalse(conn.isOpen()); Assert.assertFalse(conn.isOpen());
Assert.assertEquals(0, localServer.getAcceptedConnectionCount()); Assert.assertEquals(0, localServer.getAcceptedConnectionCount());
@ -573,16 +573,16 @@ public class TestConnectionManagement extends LocalServerTestBase {
abortingThread.join(5000); abortingThread.join(5000);
if(throwRef.get() != null) { if(throwRef.get() != null) {
throw new RuntimeException(throwRef.get()); throw new RuntimeException(throwRef.get());
} }
Assert.assertFalse(conn.isOpen()); Assert.assertFalse(conn.isOpen());
// Give the server a bit of time to accept the connection, but // Give the server a bit of time to accept the connection, but
// ensure that it can accept it. // ensure that it can accept it.
for(int i = 0; i < 10; i++) { for(int i = 0; i < 10; i++) {
if(localServer.getAcceptedConnectionCount() == 1) { if(localServer.getAcceptedConnectionCount() == 1) {
break; break;
} }
Thread.sleep(100); Thread.sleep(100);
} }
Assert.assertEquals(1, localServer.getAcceptedConnectionCount()); Assert.assertEquals(1, localServer.getAcceptedConnectionCount());
@ -608,16 +608,16 @@ public class TestConnectionManagement extends LocalServerTestBase {
void waitForState() throws InterruptedException { void waitForState() throws InterruptedException {
if(!waitLatch.await(1, TimeUnit.SECONDS)) { if(!waitLatch.await(1, TimeUnit.SECONDS)) {
throw new RuntimeException("waited too long"); throw new RuntimeException("waited too long");
} }
} }
void latch() { void latch() {
waitLatch.countDown(); waitLatch.countDown();
try { try {
if (!continueLatch.await(60, TimeUnit.SECONDS)) { if (!continueLatch.await(60, TimeUnit.SECONDS)) {
throw new RuntimeException("waited too long!"); throw new RuntimeException("waited too long!");
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -644,23 +644,23 @@ public class TestConnectionManagement extends LocalServerTestBase {
final InetSocketAddress localAddress, final InetSocketAddress localAddress,
final HttpContext context) throws IOException, ConnectTimeoutException { final HttpContext context) throws IOException, ConnectTimeoutException {
if(waitPolicy == WaitPolicy.BEFORE_CONNECT) { if(waitPolicy == WaitPolicy.BEFORE_CONNECT) {
latch(); latch();
} }
Socket socket = delegate.connectSocket( Socket socket = delegate.connectSocket(
connectTimeout, sock, host, remoteAddress, localAddress, context); connectTimeout, sock, host, remoteAddress, localAddress, context);
if(waitPolicy == WaitPolicy.AFTER_CONNECT) { if(waitPolicy == WaitPolicy.AFTER_CONNECT) {
latch(); latch();
} }
return socket; return socket;
} }
public Socket createSocket(final HttpContext context) throws IOException { public Socket createSocket(final HttpContext context) throws IOException {
if(waitPolicy == WaitPolicy.BEFORE_CREATE) { if(waitPolicy == WaitPolicy.BEFORE_CREATE) {
latch(); latch();
} }
return delegate.createSocket(context); return delegate.createSocket(context);
} }

View File

@ -83,8 +83,8 @@ public class EchoHandler
HttpEntity entity = null; HttpEntity entity = null;
if (request instanceof HttpEntityEnclosingRequest) { if (request instanceof HttpEntityEnclosingRequest) {
entity = ((HttpEntityEnclosingRequest)request).getEntity(); entity = ((HttpEntityEnclosingRequest)request).getEntity();
} }
// For some reason, just putting the incoming entity into // For some reason, just putting the incoming entity into
// the response will not work. We have to buffer the message. // the response will not work. We have to buffer the message.

View File

@ -273,10 +273,10 @@ public class LocalTestServer {
StringBuilder sb = new StringBuilder(80); StringBuilder sb = new StringBuilder(80);
sb.append("LocalTestServer/"); sb.append("LocalTestServer/");
if (ssock == null) { if (ssock == null) {
sb.append("stopped"); sb.append("stopped");
} else { } else {
sb.append(ssock.getLocalSocketAddress()); sb.append(ssock.getLocalSocketAddress());
} }
return sb.toString(); return sb.toString();
} }