Style-check to enforce unused import and final variable checks

git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@1491511 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Oleg Kalnichevski 2013-06-10 15:52:49 +00:00
parent 69057e17ba
commit b1c387e986
144 changed files with 711 additions and 847 deletions

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?eclipse-pydev version="1.0"?>
<pydev_project>
<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property>
<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.7</pydev_property>
</pydev_project>

View File

@ -26,13 +26,12 @@
<module name="AvoidStarImport"/> <module name="AvoidStarImport"/>
<module name="IllegalImport" /> <module name="IllegalImport" />
<module name="RedundantImport" /> <module name="RedundantImport" />
<module name="UnusedImports"/>
<module name="EqualsHashCode"/>
</module> </module>
<module name="Header"> <module name="Header">
<property name="headerFile" value="asl2.header" /> <property name="headerFile" value="asl2.header" />
</module> </module>
<module name="FileLength">
<property name="max" value="10000" />
</module>
<module name="FileTabCharacter"> <module name="FileTabCharacter">
<property name="eachLine" value="true"/> <property name="eachLine" value="true"/>
</module> </module>

View File

@ -33,7 +33,6 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion; import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine; import org.apache.http.StatusLine;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
@ -43,10 +42,10 @@ import org.apache.http.protocol.HTTP;
import org.apache.http.util.Args; import org.apache.http.util.Args;
/** /**
* Structure used to store an {@link HttpResponse} in a cache. Some entries * Structure used to store an {@link org.apache.http.HttpResponse} in a cache.
* can optionally depend on system resources that may require explicit * Some entries can optionally depend on system resources that may require
* deallocation. In such a case {@link #getResource()} should return a non * explicit deallocation. In such a case {@link #getResource()} should return
* null instance of {@link Resource} that must be deallocated by calling * a non null instance of {@link Resource} that must be deallocated by calling
* {@link Resource#dispose()} method when no longer used. * {@link Resource#dispose()} method when no longer used.
* *
* @since 4.1 * @since 4.1
@ -139,29 +138,32 @@ public class HttpCacheEntry implements Serializable {
} }
/** /**
* Returns the {@link StatusLine} from the origin {@link HttpResponse}. * Returns the {@link StatusLine} from the origin
* {@link org.apache.http.HttpResponse}.
*/ */
public StatusLine getStatusLine() { public StatusLine getStatusLine() {
return this.statusLine; return this.statusLine;
} }
/** /**
* Returns the {@link ProtocolVersion} from the origin {@link HttpResponse}. * Returns the {@link ProtocolVersion} from the origin
* {@link org.apache.http.HttpResponse}.
*/ */
public ProtocolVersion getProtocolVersion() { public ProtocolVersion getProtocolVersion() {
return this.statusLine.getProtocolVersion(); return this.statusLine.getProtocolVersion();
} }
/** /**
* Gets the reason phrase from the origin {@link HttpResponse}, for example, * Gets the reason phrase from the origin
* "Not Modified". * {@link org.apache.http.HttpResponse}, for example, "Not Modified".
*/ */
public String getReasonPhrase() { public String getReasonPhrase() {
return this.statusLine.getReasonPhrase(); return this.statusLine.getReasonPhrase();
} }
/** /**
* Returns the HTTP response code from the origin {@link HttpResponse}. * Returns the HTTP response code from the origin
* {@link org.apache.http.HttpResponse}.
*/ */
public int getStatusCode() { public int getStatusCode() {
return this.statusLine.getStatusCode(); return this.statusLine.getStatusCode();

View File

@ -27,7 +27,6 @@
package org.apache.http.impl.client.cache; package org.apache.http.impl.client.cache;
import java.io.IOException; import java.io.IOException;
import java.util.LinkedHashMap;
import org.apache.http.annotation.ThreadSafe; import org.apache.http.annotation.ThreadSafe;
import org.apache.http.client.cache.HttpCacheEntry; import org.apache.http.client.cache.HttpCacheEntry;
@ -36,11 +35,11 @@ import org.apache.http.client.cache.HttpCacheUpdateCallback;
/** /**
* Basic {@link HttpCacheStorage} implementation backed by an instance of * Basic {@link HttpCacheStorage} implementation backed by an instance of
* {@link LinkedHashMap}. In other words, cache entries and the cached * {@link java.util.LinkedHashMap}. In other words, cache entries and
* response bodies are held in-memory. This cache does NOT deallocate * the cached response bodies are held in-memory. This cache does NOT
* resources associated with the cache entries; it is intended for use * deallocate resources associated with the cache entries; it is intended
* with {@link HeapResource} and similar. This is the default cache * for use with {@link HeapResource} and similar. This is the default cache
* storage backend used by {@link CachingHttpClient}. * storage backend used by {@link CachingHttpClients}.
* *
* @since 4.1 * @since 4.1
*/ */

View File

@ -28,8 +28,6 @@ package org.apache.http.impl.client.cache;
import java.util.Date; import java.util.Date;
import net.sf.ehcache.CacheEntry;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
@ -44,7 +42,7 @@ import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HTTP;
/** /**
* Rebuilds an {@link HttpResponse} from a {@link CacheEntry} * Rebuilds an {@link HttpResponse} from a {@link net.sf.ehcache.CacheEntry}
* *
* @since 4.1 * @since 4.1
*/ */

View File

@ -30,7 +30,6 @@ import java.util.Map;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HeaderElement; import org.apache.http.HeaderElement;
import org.apache.http.HttpRequest;
import org.apache.http.ProtocolException; import org.apache.http.ProtocolException;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
import org.apache.http.client.cache.HeaderConstants; import org.apache.http.client.cache.HeaderConstants;
@ -45,8 +44,9 @@ class ConditionalRequestBuilder {
/** /**
* When a {@link HttpCacheEntry} is stale but 'might' be used as a response * When a {@link HttpCacheEntry} is stale but 'might' be used as a response
* to an {@link HttpRequest} we will attempt to revalidate the entry with * to an {@link org.apache.http.HttpRequest} we will attempt to revalidate
* the origin. Build the origin {@link HttpRequest} here and return it. * the entry with the origin. Build the origin {@link org.apache.http.HttpRequest}
* here and return it.
* *
* @param request the original request from the caller * @param request the original request from the caller
* @param cacheEntry the entry that needs to be re-validated * @param cacheEntry the entry that needs to be re-validated
@ -83,10 +83,11 @@ class ConditionalRequestBuilder {
} }
/** /**
* When a {@link HttpCacheEntry} does not exist for a specific {@link HttpRequest} * When a {@link HttpCacheEntry} does not exist for a specific
* we attempt to see if an existing {@link HttpCacheEntry} is appropriate by building * {@link org.apache.http.HttpRequest} we attempt to see if an existing
* a conditional {@link HttpRequest} using the variants' ETag values. If no such values * {@link HttpCacheEntry} is appropriate by building a conditional
* exist, the request is unmodified * {@link org.apache.http.HttpRequest} using the variants' ETag values.
* If no such values exist, the request is unmodified
* *
* @param request the original request from the caller * @param request the original request from the caller
* @param variants * @param variants

View File

@ -72,7 +72,7 @@ public class DefaultFailureCache implements FailureCache {
return storedErrorCode != null ? storedErrorCode.getErrorCount() : 0; return storedErrorCode != null ? storedErrorCode.getErrorCount() : 0;
} }
public void resetErrorCount(String identifier) { public void resetErrorCount(final String identifier) {
if (identifier == null) { if (identifier == null) {
throw new IllegalArgumentException("identifier may not be null"); throw new IllegalArgumentException("identifier may not be null");
} }
@ -106,7 +106,7 @@ public class DefaultFailureCache implements FailureCache {
} }
} }
else { else {
int errorCount = oldValue.getErrorCount(); final int errorCount = oldValue.getErrorCount();
if (errorCount == Integer.MAX_VALUE) { if (errorCount == Integer.MAX_VALUE) {
return; return;
} }

View File

@ -76,12 +76,15 @@ public class ExponentialBackOffSchedulingStrategy implements SchedulingStrategy
* @see #DEFAULT_MAX_EXPIRY_IN_MILLIS * @see #DEFAULT_MAX_EXPIRY_IN_MILLIS
*/ */
public ExponentialBackOffSchedulingStrategy(final CacheConfig cacheConfig) { public ExponentialBackOffSchedulingStrategy(final CacheConfig cacheConfig) {
this(cacheConfig, DEFAULT_BACK_OFF_RATE, DEFAULT_INITIAL_EXPIRY_IN_MILLIS, DEFAULT_MAX_EXPIRY_IN_MILLIS); this(cacheConfig,
DEFAULT_BACK_OFF_RATE,
DEFAULT_INITIAL_EXPIRY_IN_MILLIS,
DEFAULT_MAX_EXPIRY_IN_MILLIS);
} }
/** /**
* Create a new scheduling strategy by using a fixed pool of worker threads and the given parameters to calculated * Create a new scheduling strategy by using a fixed pool of worker threads and the
* the delay. * given parameters to calculated the delay.
* *
* @param cacheConfig the thread pool configuration to be used; not <code>null</code> * @param cacheConfig the thread pool configuration to be used; not <code>null</code>
* @param backOffRate the back off rate to be used; not negative * @param backOffRate the back off rate to be used; not negative
@ -90,24 +93,38 @@ public class ExponentialBackOffSchedulingStrategy implements SchedulingStrategy
* @see org.apache.http.impl.client.cache.CacheConfig#getAsynchronousWorkersMax() * @see org.apache.http.impl.client.cache.CacheConfig#getAsynchronousWorkersMax()
* @see ExponentialBackOffSchedulingStrategy * @see ExponentialBackOffSchedulingStrategy
*/ */
public ExponentialBackOffSchedulingStrategy(final CacheConfig cacheConfig, final long backOffRate, final long initialExpiryInMillis, final long maxExpiryInMillis) { public ExponentialBackOffSchedulingStrategy(
this(createThreadPoolFromCacheConfig(cacheConfig), backOffRate, initialExpiryInMillis, maxExpiryInMillis); final CacheConfig cacheConfig,
final long backOffRate,
final long initialExpiryInMillis,
final long maxExpiryInMillis) {
this(createThreadPoolFromCacheConfig(cacheConfig),
backOffRate,
initialExpiryInMillis,
maxExpiryInMillis);
} }
private static ScheduledThreadPoolExecutor createThreadPoolFromCacheConfig(final CacheConfig cacheConfig) { private static ScheduledThreadPoolExecutor createThreadPoolFromCacheConfig(
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(cacheConfig.getAsynchronousWorkersMax()); final CacheConfig cacheConfig) {
final ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(
cacheConfig.getAsynchronousWorkersMax());
scheduledThreadPoolExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); scheduledThreadPoolExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
return scheduledThreadPoolExecutor; return scheduledThreadPoolExecutor;
} }
ExponentialBackOffSchedulingStrategy(final ScheduledExecutorService executor, final long backOffRate, final long initialExpiryInMillis, final long maxExpiryInMillis) { ExponentialBackOffSchedulingStrategy(
final ScheduledExecutorService executor,
final long backOffRate,
final long initialExpiryInMillis,
final long maxExpiryInMillis) {
this.executor = checkNotNull("executor", executor); this.executor = checkNotNull("executor", executor);
this.backOffRate = checkNotNegative("backOffRate", backOffRate); this.backOffRate = checkNotNegative("backOffRate", backOffRate);
this.initialExpiryInMillis = checkNotNegative("initialExpiryInMillis", initialExpiryInMillis); this.initialExpiryInMillis = checkNotNegative("initialExpiryInMillis", initialExpiryInMillis);
this.maxExpiryInMillis = checkNotNegative("maxExpiryInMillis", maxExpiryInMillis); this.maxExpiryInMillis = checkNotNegative("maxExpiryInMillis", maxExpiryInMillis);
} }
public void schedule(final AsynchronousValidationRequest revalidationRequest) { public void schedule(
final AsynchronousValidationRequest revalidationRequest) {
checkNotNull("revalidationRequest", revalidationRequest); checkNotNull("revalidationRequest", revalidationRequest);
final int consecutiveFailedAttempts = revalidationRequest.getConsecutiveFailedAttempts(); final int consecutiveFailedAttempts = revalidationRequest.getConsecutiveFailedAttempts();
final long delayInMillis = calculateDelayInMillis(consecutiveFailedAttempts); final long delayInMillis = calculateDelayInMillis(consecutiveFailedAttempts);
@ -132,7 +149,8 @@ public class ExponentialBackOffSchedulingStrategy implements SchedulingStrategy
protected long calculateDelayInMillis(final int consecutiveFailedAttempts) { protected long calculateDelayInMillis(final int consecutiveFailedAttempts) {
if (consecutiveFailedAttempts > 0) { if (consecutiveFailedAttempts > 0) {
final long delayInSeconds = (long) (initialExpiryInMillis * Math.pow(backOffRate, consecutiveFailedAttempts - 1)); final long delayInSeconds = (long) (initialExpiryInMillis *
Math.pow(backOffRate, consecutiveFailedAttempts - 1));
return Math.min(delayInSeconds, maxExpiryInMillis); return Math.min(delayInSeconds, maxExpiryInMillis);
} }
else { else {

View File

@ -40,7 +40,7 @@ public class FailureCacheValue {
private final String key; private final String key;
private final int errorCount; private final int errorCount;
public FailureCacheValue(String key, int errorCount) { public FailureCacheValue(final String key, final int errorCount) {
this.creationTimeInNanos = System.nanoTime(); this.creationTimeInNanos = System.nanoTime();
this.key = key; this.key = key;
this.errorCount = errorCount; this.errorCount = errorCount;
@ -61,6 +61,7 @@ public class FailureCacheValue {
@Override @Override
public String toString() { public String toString() {
return "[entry creationTimeInNanos=" + creationTimeInNanos + "; key=" + key + "; errorCount=" + errorCount + ']'; return "[entry creationTimeInNanos=" + creationTimeInNanos + "; " +
"key=" + key + "; errorCount=" + errorCount + ']';
} }
} }

View File

@ -76,7 +76,7 @@ public class HeapResourceFactory implements ResourceFactory {
return createResource(body); return createResource(body);
} }
Resource createResource(byte[] buf) { Resource createResource(final byte[] buf) {
return new HeapResource(buf); return new HeapResource(buf);
} }

View File

@ -28,7 +28,6 @@ package org.apache.http.impl.client.cache;
import java.io.Closeable; import java.io.Closeable;
import java.io.IOException; import java.io.IOException;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue; import java.lang.ref.ReferenceQueue;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
@ -42,12 +41,13 @@ import org.apache.http.util.Args;
/** /**
* {@link HttpCacheStorage} implementation capable of deallocating resources associated with * {@link HttpCacheStorage} implementation capable of deallocating resources associated with
* the cache entries. This cache keeps track of cache entries using {@link PhantomReference} * the cache entries. This cache keeps track of cache entries using
* and maintains a collection of all resources that are no longer in use. The cache, however, * {@link java.lang.ref.PhantomReference} and maintains a collection of all resources that
* does not automatically deallocates associated resources by invoking {@link Resource#dispose()} * are no longer in use. The cache, however, does not automatically deallocates associated
* method. The consumer MUST periodically call {@link #cleanResources()} method to trigger * resources by invoking {@link Resource#dispose()} method. The consumer MUST periodically
* resource deallocation. The cache can be permanently shut down using {@link #shutdown()} * call {@link #cleanResources()} method to trigger resource deallocation. The cache can be
* method. All resources associated with the entries used by the cache will be deallocated. * permanently shut down using {@link #shutdown()} method. All resources associated with
* the entries used by the cache will be deallocated.
* *
* This {@link HttpCacheStorage} implementation is intended for use with {@link FileResource} * This {@link HttpCacheStorage} implementation is intended for use with {@link FileResource}
* and similar. * and similar.

View File

@ -78,7 +78,7 @@ class ResponseCachingPolicy {
public ResponseCachingPolicy(final long maxObjectSizeBytes, public ResponseCachingPolicy(final long maxObjectSizeBytes,
final boolean sharedCache, final boolean sharedCache,
final boolean neverCache1_0ResponsesWithQueryString, final boolean neverCache1_0ResponsesWithQueryString,
boolean allow303Caching) { final boolean allow303Caching) {
this.maxObjectSizeBytes = maxObjectSizeBytes; this.maxObjectSizeBytes = maxObjectSizeBytes;
this.sharedCache = sharedCache; this.sharedCache = sharedCache;
this.neverCache1_0ResponsesWithQueryString = neverCache1_0ResponsesWithQueryString; this.neverCache1_0ResponsesWithQueryString = neverCache1_0ResponsesWithQueryString;

View File

@ -51,14 +51,13 @@
* *
*/package org.apache.http.impl.client.cache.memcached; */package org.apache.http.impl.client.cache.memcached;
import org.apache.http.client.cache.HttpCacheStorage;
/** /**
* Since the {@link HttpCacheStorage} interface expects to use variant-annotated * Since the {@link org.apache.http.client.cache.HttpCacheStorage} interface
* URLs for its storage keys, but Memcached has a maximum key size, we need to * expects to use variant-annotated URLs for its storage keys, but Memcached
* support mapping storage keys to cache keys. Clients can implement this * has a maximum key size, we need to support mapping storage keys to cache
* interface to change the way the mapping is done (for example, to add a prefix * keys. Clients can implement this interface to change the way the mapping
* to all cache keys to provide a form of memcached namespacing). * is done (for example, to add a prefix to all cache keys to provide a form
* of memcached namespacing).
*/ */
public interface KeyHashingScheme { public interface KeyHashingScheme {

View File

@ -32,7 +32,9 @@ public class TestCachingHttpClientBuilder {
@Test @Test
public void testAsynchronousWorkersMax0() throws Exception { public void testAsynchronousWorkersMax0() throws Exception {
CacheConfig cacheConfig = CacheConfig.custom().setAsynchronousWorkersMax(0).build(); final CacheConfig cacheConfig = CacheConfig.custom()
.setAsynchronousWorkersMax(0)
.build();
// Asynchronous validation should be disabled but we should not get an // Asynchronous validation should be disabled but we should not get an
// Exception // Exception
CachingHttpClientBuilder.create().setCacheConfig(cacheConfig).build(); CachingHttpClientBuilder.create().setCacheConfig(cacheConfig).build();

View File

@ -41,7 +41,7 @@ public class TestDefaultFailureCache
failureCache.increaseErrorCount(IDENTIFIER); failureCache.increaseErrorCount(IDENTIFIER);
failureCache.resetErrorCount(IDENTIFIER); failureCache.resetErrorCount(IDENTIFIER);
int errorCount = failureCache.getErrorCount(IDENTIFIER); final int errorCount = failureCache.getErrorCount(IDENTIFIER);
Assert.assertEquals(0, errorCount); Assert.assertEquals(0, errorCount);
} }
@ -51,7 +51,7 @@ public class TestDefaultFailureCache
failureCache.increaseErrorCount(IDENTIFIER); failureCache.increaseErrorCount(IDENTIFIER);
failureCache.increaseErrorCount(IDENTIFIER); failureCache.increaseErrorCount(IDENTIFIER);
int errorCount = failureCache.getErrorCount(IDENTIFIER); final int errorCount = failureCache.getErrorCount(IDENTIFIER);
Assert.assertEquals(3, errorCount); Assert.assertEquals(3, errorCount);
} }
@ -63,7 +63,7 @@ public class TestDefaultFailureCache
failureCache.increaseErrorCount("c"); failureCache.increaseErrorCount("c");
failureCache.increaseErrorCount("d"); failureCache.increaseErrorCount("d");
int errorCount = failureCache.getErrorCount("a"); final int errorCount = failureCache.getErrorCount("a");
Assert.assertEquals(0, errorCount); Assert.assertEquals(0, errorCount);
} }
} }

View File

@ -58,7 +58,7 @@ public class TestExponentialBackingOffSchedulingStrategy {
@Test @Test
public void testScheduleWithoutPreviousError() { public void testScheduleWithoutPreviousError() {
AsynchronousValidationRequest request = createAsynchronousValidationRequest(withErrorCount(0)); final AsynchronousValidationRequest request = createAsynchronousValidationRequest(withErrorCount(0));
expectRequestScheduledWithoutDelay(request); expectRequestScheduledWithoutDelay(request);
@ -69,7 +69,7 @@ public class TestExponentialBackingOffSchedulingStrategy {
@Test @Test
public void testScheduleWithOneFailedAttempt() { public void testScheduleWithOneFailedAttempt() {
AsynchronousValidationRequest request = createAsynchronousValidationRequest(withErrorCount(1)); final AsynchronousValidationRequest request = createAsynchronousValidationRequest(withErrorCount(1));
expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(6)); expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(6));
@ -80,7 +80,7 @@ public class TestExponentialBackingOffSchedulingStrategy {
@Test @Test
public void testScheduleWithTwoFailedAttempts() { public void testScheduleWithTwoFailedAttempts() {
AsynchronousValidationRequest request = createAsynchronousValidationRequest(withErrorCount(2)); final AsynchronousValidationRequest request = createAsynchronousValidationRequest(withErrorCount(2));
expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(60)); expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(60));
@ -91,7 +91,7 @@ public class TestExponentialBackingOffSchedulingStrategy {
@Test @Test
public void testScheduleWithThreeFailedAttempts() { public void testScheduleWithThreeFailedAttempts() {
AsynchronousValidationRequest request = createAsynchronousValidationRequest(withErrorCount(3)); final AsynchronousValidationRequest request = createAsynchronousValidationRequest(withErrorCount(3));
expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(600)); expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(600));
@ -102,7 +102,7 @@ public class TestExponentialBackingOffSchedulingStrategy {
@Test @Test
public void testScheduleWithFourFailedAttempts() { public void testScheduleWithFourFailedAttempts() {
AsynchronousValidationRequest request = createAsynchronousValidationRequest(withErrorCount(4)); final AsynchronousValidationRequest request = createAsynchronousValidationRequest(withErrorCount(4));
expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(6000)); expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(6000));
@ -113,7 +113,7 @@ public class TestExponentialBackingOffSchedulingStrategy {
@Test @Test
public void testScheduleWithFiveFailedAttempts() { public void testScheduleWithFiveFailedAttempts() {
AsynchronousValidationRequest request = createAsynchronousValidationRequest(withErrorCount(5)); final AsynchronousValidationRequest request = createAsynchronousValidationRequest(withErrorCount(5));
expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(60000)); expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(60000));
@ -124,7 +124,7 @@ public class TestExponentialBackingOffSchedulingStrategy {
@Test @Test
public void testScheduleWithSixFailedAttempts() { public void testScheduleWithSixFailedAttempts() {
AsynchronousValidationRequest request = createAsynchronousValidationRequest(withErrorCount(6)); final AsynchronousValidationRequest request = createAsynchronousValidationRequest(withErrorCount(6));
expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(86400)); expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(86400));
@ -135,7 +135,7 @@ public class TestExponentialBackingOffSchedulingStrategy {
@Test @Test
public void testScheduleWithMaxNumberOfFailedAttempts() { public void testScheduleWithMaxNumberOfFailedAttempts() {
AsynchronousValidationRequest request = createAsynchronousValidationRequest(withErrorCount(Integer.MAX_VALUE)); final AsynchronousValidationRequest request = createAsynchronousValidationRequest(withErrorCount(Integer.MAX_VALUE));
expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(86400)); expectRequestScheduledWithDelay(request, TimeUnit.SECONDS.toMillis(86400));

View File

@ -49,32 +49,32 @@ final class PropertiesUtils {
register(new DoublePropertyConverter(), double.class, Double.class); register(new DoublePropertyConverter(), double.class, Double.class);
} }
private static void register(PropertyConverter<?> converter, Class<?>...targetTypes) { private static void register(final PropertyConverter<?> converter, final Class<?>...targetTypes) {
for (Class<?> targetType : targetTypes) { for (final Class<?> targetType : targetTypes) {
CONVERTERS_REGISTRY.put(targetType, converter); CONVERTERS_REGISTRY.put(targetType, converter);
} }
} }
public static <T> T to(Object propValue, Class<T> targetType, T defaultValue) { public static <T> T to(final Object propValue, final Class<T> targetType, final T defaultValue) {
if (propValue == null) { Object v = propValue;
if (v == null) {
return defaultValue; return defaultValue;
} }
if (!targetType.isArray()) { if (!targetType.isArray()) {
propValue = toObject(propValue); v = toObject(v);
} }
if (targetType.isInstance(propValue)) { if (targetType.isInstance(v)) {
return targetType.cast(propValue); return targetType.cast(v);
} }
if (CONVERTERS_REGISTRY.containsKey(targetType)) { if (CONVERTERS_REGISTRY.containsKey(targetType)) {
@SuppressWarnings("unchecked") // type driven by targetType @SuppressWarnings("unchecked") final // type driven by targetType
PropertyConverter<T> converter = (PropertyConverter<T>) CONVERTERS_REGISTRY.get(targetType); PropertyConverter<T> converter = (PropertyConverter<T>) CONVERTERS_REGISTRY.get(targetType);
try { try {
return converter.to(propValue); return converter.to(v);
} catch (Throwable t) { } catch (final Exception ignore) {
// don't care, fall through to default value
} }
} }
@ -90,14 +90,14 @@ final class PropertiesUtils {
* *
* @param propValue the parameter to convert. * @param propValue the parameter to convert.
*/ */
private static Object toObject(Object propValue) { private static Object toObject(final Object propValue) {
if (propValue.getClass().isArray()) { if (propValue.getClass().isArray()) {
Object[] prop = (Object[]) propValue; final Object[] prop = (Object[]) propValue;
return prop.length > 0 ? prop[0] : null; return prop.length > 0 ? prop[0] : null;
} }
if (propValue instanceof Collection<?>) { if (propValue instanceof Collection<?>) {
Collection<?> prop = (Collection<?>) propValue; final Collection<?> prop = (Collection<?>) propValue;
return prop.isEmpty() ? null : prop.iterator().next(); return prop.isEmpty() ? null : prop.iterator().next();
} }
@ -119,7 +119,7 @@ final class PropertiesUtils {
private static class BooleanPropertyConverter implements PropertyConverter<Boolean> { private static class BooleanPropertyConverter implements PropertyConverter<Boolean> {
public Boolean to(Object propValue) { public Boolean to(final Object propValue) {
return Boolean.valueOf(String.valueOf(propValue)); return Boolean.valueOf(String.valueOf(propValue));
} }
@ -127,7 +127,7 @@ final class PropertiesUtils {
private static class StringPropertyConverter implements PropertyConverter<String> { private static class StringPropertyConverter implements PropertyConverter<String> {
public String to(Object propValue) { public String to(final Object propValue) {
return String.valueOf(propValue); return String.valueOf(propValue);
} }
@ -135,7 +135,7 @@ final class PropertiesUtils {
private static class StringArrayPropertyConverter implements PropertyConverter<String[]> { private static class StringArrayPropertyConverter implements PropertyConverter<String[]> {
public String[] to(Object propValue) { public String[] to(final Object propValue) {
if (propValue instanceof String) { if (propValue instanceof String) {
// single string // single string
return new String[] { (String) propValue }; return new String[] { (String) propValue };
@ -143,9 +143,9 @@ final class PropertiesUtils {
if (propValue.getClass().isArray()) { if (propValue.getClass().isArray()) {
// other array // other array
Object[] valueArray = (Object[]) propValue; final Object[] valueArray = (Object[]) propValue;
List<String> values = new ArrayList<String>(valueArray.length); final List<String> values = new ArrayList<String>(valueArray.length);
for (Object value : valueArray) { for (final Object value : valueArray) {
if (value != null) { if (value != null) {
values.add(value.toString()); values.add(value.toString());
} }
@ -156,9 +156,9 @@ final class PropertiesUtils {
if (propValue instanceof Collection<?>) { if (propValue instanceof Collection<?>) {
// collection // collection
Collection<?> valueCollection = (Collection<?>) propValue; final Collection<?> valueCollection = (Collection<?>) propValue;
List<String> valueList = new ArrayList<String>(valueCollection.size()); final List<String> valueList = new ArrayList<String>(valueCollection.size());
for (Object value : valueCollection) { for (final Object value : valueCollection) {
if (value != null) { if (value != null) {
valueList.add(value.toString()); valueList.add(value.toString());
} }
@ -174,7 +174,7 @@ final class PropertiesUtils {
private static class IntegerPropertyConverter implements PropertyConverter<Integer> { private static class IntegerPropertyConverter implements PropertyConverter<Integer> {
public Integer to(Object propValue) { public Integer to(final Object propValue) {
return Integer.valueOf(String.valueOf(propValue)); return Integer.valueOf(String.valueOf(propValue));
} }
@ -182,7 +182,7 @@ final class PropertiesUtils {
private static class LongPropertyConverter implements PropertyConverter<Long> { private static class LongPropertyConverter implements PropertyConverter<Long> {
public Long to(Object propValue) { public Long to(final Object propValue) {
return Long.valueOf(String.valueOf(propValue)); return Long.valueOf(String.valueOf(propValue));
} }
@ -190,7 +190,7 @@ final class PropertiesUtils {
private static class DoublePropertyConverter implements PropertyConverter<Double> { private static class DoublePropertyConverter implements PropertyConverter<Double> {
public Double to(Object propValue) { public Double to(final Object propValue) {
return Double.valueOf(String.valueOf(propValue)); return Double.valueOf(String.valueOf(propValue));
} }

View File

@ -116,13 +116,15 @@ public final class TestPropertiesUtils {
assertConverted(789d, "not a double", Double.class, 789d); assertConverted(789d, "not a double", Double.class, 789d);
} }
private static <T> void assertConverted(T expected, Object propValue, Class<T> targetType, T defaultValue) { private static <T> void assertConverted(
T actual = to(propValue, targetType, defaultValue); final T expected, final Object propValue, final Class<T> targetType, final T defaultValue) {
final T actual = to(propValue, targetType, defaultValue);
assertEquals(expected, actual); assertEquals(expected, actual);
} }
private static <T> void assertConvertedArray(T[] expected, Object propValue, Class<T[]> targetType, T[] defaultValue) { private static <T> void assertConvertedArray(
T[] actual = to(propValue, targetType, defaultValue); final T[] expected, final Object propValue, final Class<T[]> targetType, final T[] defaultValue) {
final T[] actual = to(propValue, targetType, defaultValue);
assertArrayEquals(expected, actual); assertArrayEquals(expected, actual);
} }

View File

@ -30,7 +30,6 @@ package org.apache.http.examples.client;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
@ -39,7 +38,7 @@ import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
/** /**
* How to send a request via proxy using {@link HttpClient}. * How to send a request via proxy.
* *
* @since 4.0 * @since 4.0
*/ */

View File

@ -36,7 +36,6 @@ import java.net.SocketTimeoutException;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.protocol.HttpClientContext;
@ -51,7 +50,7 @@ import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
/** /**
* How to send a request via SOCKS proxy using {@link HttpClient}. * How to send a request via SOCKS proxy.
* *
* @since 4.1 * @since 4.1
*/ */

View File

@ -35,7 +35,6 @@ import java.util.concurrent.ConcurrentHashMap;
import org.apache.http.HttpRequest; import org.apache.http.HttpRequest;
import org.apache.http.annotation.ThreadSafe; import org.apache.http.annotation.ThreadSafe;
import org.apache.http.config.Lookup; import org.apache.http.config.Lookup;
import org.apache.http.config.Registry;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
@ -47,7 +46,7 @@ import org.apache.http.util.Args;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link Registry} * @deprecated (4.3) use {@link org.apache.http.config.Registry}
*/ */
@ThreadSafe @ThreadSafe
@Deprecated @Deprecated

View File

@ -63,7 +63,7 @@ public class NTCredentials implements Credentials, Serializable {
public NTCredentials(final String usernamePassword) { public NTCredentials(final String usernamePassword) {
super(); super();
Args.notNull(usernamePassword, "Username:password string"); Args.notNull(usernamePassword, "Username:password string");
String username; final String username;
final int atColon = usernamePassword.indexOf(':'); final int atColon = usernamePassword.indexOf(':');
if (atColon >= 0) { if (atColon >= 0) {
username = usernamePassword.substring(0, atColon); username = usernamePassword.substring(0, atColon);

View File

@ -27,17 +27,14 @@
package org.apache.http.auth.params; package org.apache.http.auth.params;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.client.config.RequestConfig;
/** /**
* Parameter names for HTTP authentication classes. * Parameter names for HTTP authentication classes.
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link RequestConfig} and constructor parameters of * @deprecated (4.3) use {@link org.apache.http.client.config.RequestConfig}
* {@link AuthSchemeProvider}s. * and constructor parameters of
* {@link org.apache.http.auth.AuthSchemeProvider}s.
*/ */
@Deprecated @Deprecated
public interface AuthPNames { public interface AuthPNames {
@ -51,24 +48,26 @@ public interface AuthPNames {
public static final String CREDENTIAL_CHARSET = "http.auth.credential-charset"; public static final String CREDENTIAL_CHARSET = "http.auth.credential-charset";
/** /**
* Defines the order of preference for supported {@link AuthScheme}s when * Defines the order of preference for supported
* authenticating with the target host. * {@link org.apache.http.auth.AuthScheme}s when authenticating with
* the target host.
* <p> * <p>
* This parameter expects a value of type {@link java.util.Collection}. The * This parameter expects a value of type {@link java.util.Collection}. The
* collection is expected to contain {@link String} instances representing * collection is expected to contain {@link String} instances representing
* a name of an authentication scheme as returned by * a name of an authentication scheme as returned by
* {@link AuthScheme#getSchemeName()}. * {@link org.apache.http.auth.AuthScheme#getSchemeName()}.
*/ */
public static final String TARGET_AUTH_PREF = "http.auth.target-scheme-pref"; public static final String TARGET_AUTH_PREF = "http.auth.target-scheme-pref";
/** /**
* Defines the order of preference for supported {@link AuthScheme}s when * Defines the order of preference for supported
* authenticating with the proxy host. * {@link org.apache.http.auth.AuthScheme}s when authenticating with the
* proxy host.
* <p> * <p>
* This parameter expects a value of type {@link java.util.Collection}. The * This parameter expects a value of type {@link java.util.Collection}. The
* collection is expected to contain {@link String} instances representing * collection is expected to contain {@link String} instances representing
* a name of an authentication scheme as returned by * a name of an authentication scheme as returned by
* {@link AuthScheme#getSchemeName()}. * {@link org.apache.http.auth.AuthScheme#getSchemeName()}.
*/ */
public static final String PROXY_AUTH_PREF = "http.auth.proxy-scheme-pref"; public static final String PROXY_AUTH_PREF = "http.auth.proxy-scheme-pref";

View File

@ -27,8 +27,6 @@
package org.apache.http.auth.params; package org.apache.http.auth.params;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.params.HttpAbstractParamBean; import org.apache.http.params.HttpAbstractParamBean;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
@ -39,8 +37,9 @@ import org.apache.http.params.HttpParams;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link RequestConfig} and constructor parameters of * @deprecated (4.3) use {@link org.apache.http.client.config.RequestConfig}
* {@link AuthSchemeProvider}s. * and constructor parameters of
* {@link org.apache.http.auth.AuthSchemeProvider}s.
*/ */
@Deprecated @Deprecated
public class AuthParamBean extends HttpAbstractParamBean { public class AuthParamBean extends HttpAbstractParamBean {

View File

@ -28,8 +28,6 @@
package org.apache.http.auth.params; package org.apache.http.auth.params;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HTTP;
import org.apache.http.util.Args; import org.apache.http.util.Args;
@ -40,8 +38,9 @@ import org.apache.http.util.Args;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link RequestConfig} and constructor parameters of * @deprecated (4.3) use {@link org.apache.http.client.config.RequestConfig}
* {@link AuthSchemeProvider}s. * and constructor parameters of
* {@link org.apache.http.auth.AuthSchemeProvider}s.
*/ */
@Immutable @Immutable
@Deprecated @Deprecated

View File

@ -27,18 +27,16 @@
package org.apache.http.client; package org.apache.http.client;
import java.io.IOException;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.HttpRequest; import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import java.io.IOException;
/** /**
* This interface represents only the most basic contract for HTTP request * This interface represents only the most basic contract for HTTP request
* execution. It imposes no restrictions or particular details on the request * execution. It imposes no restrictions or particular details on the request
@ -115,7 +113,8 @@ public interface HttpClient {
* *
* @return the default parameters * @return the default parameters
* *
* @deprecated (4.3) use {@link RequestConfig}. * @deprecated (4.3) use
* {@link org.apache.http.client.config.RequestConfig}.
*/ */
@Deprecated @Deprecated
HttpParams getParams(); HttpParams getParams();
@ -125,7 +124,8 @@ public interface HttpClient {
* *
* @return the connection manager * @return the connection manager
* *
* @deprecated (4.3) use {@link HttpClientBuilder}. * @deprecated (4.3) use
* {@link org.apache.http.impl.client.HttpClientBuilder}.
*/ */
@Deprecated @Deprecated
ClientConnectionManager getConnectionManager(); ClientConnectionManager getConnectionManager();

View File

@ -31,16 +31,18 @@ import java.io.InputStream;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
/** /**
* {@link HttpEntityWrapper} responsible for handling deflate Content Coded responses. In RFC2616 * {@link org.apache.http.entity.HttpEntityWrapper} responsible for handling
* terms, <code>deflate</code> means a <code>zlib</code> stream as defined in RFC1950. Some server * deflate Content Coded responses. In RFC2616 terms, <code>deflate</code>
* implementations have misinterpreted RFC2616 to mean that a <code>deflate</code> stream as * means a <code>zlib</code> stream as defined in RFC1950. Some server
* defined in RFC1951 should be used (or maybe they did that since that's how IE behaves?). It's * implementations have misinterpreted RFC2616 to mean that a
* confusing that <code>deflate</code> in HTTP 1.1 means <code>zlib</code> streams rather than * <code>deflate</code> stream as defined in RFC1951 should be used
* <code>deflate</code> streams. We handle both types in here, since that's what is seen on the * (or maybe they did that since that's how IE behaves?). It's confusing
* internet. Moral - prefer <code>gzip</code>! * that <code>deflate</code> in HTTP 1.1 means <code>zlib</code> streams
* rather than <code>deflate</code> streams. We handle both types in here,
* since that's what is seen on the internet. Moral - prefer
* <code>gzip</code>!
* *
* @see GzipDecompressingEntity * @see GzipDecompressingEntity
* *

View File

@ -138,7 +138,7 @@ public class DeflateInputStream extends InputStream
/** Read lots of bytes. /** Read lots of bytes.
*/ */
@Override @Override
public int read(byte[] b) public int read(final byte[] b)
throws IOException throws IOException
{ {
return sourceStream.read(b); return sourceStream.read(b);
@ -147,7 +147,7 @@ public class DeflateInputStream extends InputStream
/** Read lots of specific bytes. /** Read lots of specific bytes.
*/ */
@Override @Override
public int read(byte[] b, int off, int len) public int read(final byte[] b, final int off, final int len)
throws IOException throws IOException
{ {
return sourceStream.read(b,off,len); return sourceStream.read(b,off,len);
@ -156,7 +156,7 @@ public class DeflateInputStream extends InputStream
/** Skip /** Skip
*/ */
@Override @Override
public long skip(long n) public long skip(final long n)
throws IOException throws IOException
{ {
return sourceStream.skip(n); return sourceStream.skip(n);
@ -174,7 +174,7 @@ public class DeflateInputStream extends InputStream
/** Mark. /** Mark.
*/ */
@Override @Override
public void mark(int readLimit) public void mark(final int readLimit)
{ {
sourceStream.mark(readLimit); sourceStream.mark(readLimit);
} }

View File

@ -184,7 +184,7 @@ public class EntityBuilder {
} }
public HttpEntity build() { public HttpEntity build() {
AbstractHttpEntity e; final AbstractHttpEntity e;
if (this.text != null) { if (this.text != null) {
e = new StringEntity(this.text, getContentOrDefault(ContentType.DEFAULT_TEXT)); e = new StringEntity(this.text, getContentOrDefault(ContentType.DEFAULT_TEXT));
} else if (this.binary != null) { } else if (this.binary != null) {

View File

@ -32,10 +32,10 @@ import java.util.zip.GZIPInputStream;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
/** /**
* {@link HttpEntityWrapper} for handling gzip Content Coded responses. * {@link org.apache.http.entity.HttpEntityWrapper} for handling gzip
* Content Coded responses.
* *
* @since 4.1 * @since 4.1
*/ */

View File

@ -27,13 +27,11 @@
package org.apache.http.client.methods; package org.apache.http.client.methods;
import java.io.IOException;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ClientConnectionRequest; import org.apache.http.conn.ClientConnectionRequest;
import org.apache.http.conn.ConnectionReleaseTrigger; import org.apache.http.conn.ConnectionReleaseTrigger;
import org.apache.http.conn.ManagedClientConnection;
import java.io.IOException;
/** /**
* Interface representing an HTTP request that can be aborted by shutting * Interface representing an HTTP request that can be aborted by shutting
@ -47,18 +45,19 @@ import org.apache.http.conn.ManagedClientConnection;
public interface AbortableHttpRequest { public interface AbortableHttpRequest {
/** /**
* Sets the {@link ClientConnectionRequest} callback that can be * Sets the {@link org.apache.http.conn.ClientConnectionRequest}
* used to abort a long-lived request for a connection. * callback that can be used to abort a long-lived request for a connection.
* If the request is already aborted, throws an {@link IOException}. * If the request is already aborted, throws an {@link IOException}.
* *
* @see ClientConnectionManager * @see org.apache.http.conn.ClientConnectionManager
*/ */
void setConnectionRequest(ClientConnectionRequest connRequest) throws IOException; void setConnectionRequest(ClientConnectionRequest connRequest) throws IOException;
/** /**
* Sets the {@link ConnectionReleaseTrigger} callback that can * Sets the {@link ConnectionReleaseTrigger} callback that can
* be used to abort an active connection. * be used to abort an active connection.
* Typically, this will be the {@link ManagedClientConnection} itself. * Typically, this will be the
* {@link org.apache.http.conn.ManagedClientConnection} itself.
* If the request is already aborted, throws an {@link IOException}. * If the request is already aborted, throws an {@link IOException}.
*/ */
void setReleaseTrigger(ConnectionReleaseTrigger releaseTrigger) throws IOException; void setReleaseTrigger(ConnectionReleaseTrigger releaseTrigger) throws IOException;
@ -69,12 +68,12 @@ public interface AbortableHttpRequest {
* the next execution. Aborting this request will cause all subsequent * the next execution. Aborting this request will cause all subsequent
* executions with this request to fail. * executions with this request to fail.
* *
* @see HttpClient#execute(HttpUriRequest) * @see org.apache.http.client.HttpClient#execute(HttpUriRequest)
* @see HttpClient#execute(org.apache.http.HttpHost, * @see org.apache.http.client.HttpClient#execute(org.apache.http.HttpHost,
* org.apache.http.HttpRequest) * org.apache.http.HttpRequest)
* @see HttpClient#execute(HttpUriRequest, * @see org.apache.http.client.HttpClient#execute(HttpUriRequest,
* org.apache.http.protocol.HttpContext) * org.apache.http.protocol.HttpContext)
* @see HttpClient#execute(org.apache.http.HttpHost, * @see org.apache.http.client.HttpClient#execute(org.apache.http.HttpHost,
* org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext) * org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext)
*/ */
void abort(); void abort();

View File

@ -36,7 +36,6 @@ import org.apache.http.HttpRequest;
import org.apache.http.ProtocolVersion; import org.apache.http.ProtocolVersion;
import org.apache.http.RequestLine; import org.apache.http.RequestLine;
import org.apache.http.annotation.NotThreadSafe; import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.message.AbstractHttpMessage; import org.apache.http.message.AbstractHttpMessage;
import org.apache.http.message.BasicRequestLine; import org.apache.http.message.BasicRequestLine;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
@ -157,7 +156,8 @@ public class HttpRequestWrapper extends AbstractHttpMessage implements HttpUriRe
} }
/** /**
* @deprecated (4.3) use {@link RequestConfig}. * @deprecated (4.3) use
* {@link org.apache.http.client.config.RequestConfig}.
*/ */
@Override @Override
@Deprecated @Deprecated

View File

@ -277,7 +277,7 @@ public class RequestBuilder {
} }
public HttpUriRequest build() { public HttpUriRequest build() {
HttpRequestBase result; final HttpRequestBase result;
URI uri = this.uri != null ? this.uri : URI.create("/"); URI uri = this.uri != null ? this.uri : URI.create("/");
HttpEntity entity = this.entity; HttpEntity entity = this.entity;
if (parameters != null && !parameters.isEmpty()) { if (parameters != null && !parameters.isEmpty()) {

View File

@ -27,7 +27,6 @@
package org.apache.http.client.params; package org.apache.http.client.params;
import org.apache.http.auth.params.AuthPNames; import org.apache.http.auth.params.AuthPNames;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.params.ConnConnectionPNames; import org.apache.http.conn.params.ConnConnectionPNames;
import org.apache.http.conn.params.ConnManagerPNames; import org.apache.http.conn.params.ConnManagerPNames;
import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.params.ConnRoutePNames;
@ -48,7 +47,10 @@ import org.apache.http.params.CoreProtocolPNames;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link RequestConfig} * @deprecated (4.3) use
* {@link org.apache.http.client.config.RequestConfig},
* {@link org.apache.http.config.ConnectionConfig},
* {@link org.apache.http.config.SocketConfig}
*/ */
@Deprecated @Deprecated
public interface AllClientPNames extends public interface AllClientPNames extends

View File

@ -28,14 +28,13 @@
package org.apache.http.client.params; package org.apache.http.client.params;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
import org.apache.http.client.config.AuthSchemes;
/** /**
* Standard authentication schemes supported by HttpClient. * Standard authentication schemes supported by HttpClient.
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link AuthSchemes} * @deprecated (4.3) use {@link org.apache.http.client.config.AuthSchemes}.
*/ */
@Deprecated @Deprecated
@Immutable @Immutable

View File

@ -26,14 +26,12 @@
*/ */
package org.apache.http.client.params; package org.apache.http.client.params;
import org.apache.http.client.config.RequestConfig;
/** /**
* Parameter names for HTTP client parameters. * Parameter names for HTTP client parameters.
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link RequestConfig} * @deprecated (4.3) use {@link org.apache.http.client.config.RequestConfig}.
*/ */
@Deprecated @Deprecated
public interface ClientPNames { public interface ClientPNames {

View File

@ -32,7 +32,6 @@ import java.util.Collection;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.annotation.NotThreadSafe; import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.params.HttpAbstractParamBean; import org.apache.http.params.HttpAbstractParamBean;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
@ -43,7 +42,7 @@ import org.apache.http.params.HttpParams;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link RequestConfig} * @deprecated (4.3) use {@link org.apache.http.client.config.RequestConfig}.
*/ */
@Deprecated @Deprecated
@NotThreadSafe @NotThreadSafe

View File

@ -28,14 +28,13 @@
package org.apache.http.client.params; package org.apache.http.client.params;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
import org.apache.http.client.config.CookieSpecs;
/** /**
* Standard cookie specifications supported by HttpClient. * Standard cookie specifications supported by HttpClient.
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link CookieSpecs} * @deprecated (4.3) use {@link org.apache.http.client.config.CookieSpecs}.
*/ */
@Deprecated @Deprecated
@Immutable @Immutable

View File

@ -27,7 +27,6 @@
package org.apache.http.client.params; package org.apache.http.client.params;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.util.Args; import org.apache.http.util.Args;
@ -37,7 +36,7 @@ import org.apache.http.util.Args;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link RequestConfig} * @deprecated (4.3) use {@link org.apache.http.client.config.RequestConfig}
*/ */
@Deprecated @Deprecated
@Immutable @Immutable

View File

@ -27,15 +27,13 @@
package org.apache.http.client.protocol; package org.apache.http.client.protocol;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.cookie.CookieSpecProvider;
/** /**
* {@link org.apache.http.protocol.HttpContext} attribute names for * {@link org.apache.http.protocol.HttpContext} attribute names for
* client side HTTP protocol processing. * client side HTTP protocol processing.
* *
* @since 4.0 * @since 4.0
*
* @deprecated (4.3) use {@link HttpClientContext}.
*/ */
@Deprecated @Deprecated
public interface ClientContext { public interface ClientContext {
@ -51,15 +49,13 @@ public interface ClientContext {
/** /**
* Attribute name of a {@link org.apache.http.conn.scheme.Scheme} * Attribute name of a {@link org.apache.http.conn.scheme.Scheme}
* object that represents the actual protocol scheme registry. * object that represents the actual protocol scheme registry.
*
* @deprecated (4.3) do not use
*/ */
@Deprecated @Deprecated
public static final String SCHEME_REGISTRY = "http.scheme-registry"; public static final String SCHEME_REGISTRY = "http.scheme-registry";
/** /**
* Attribute name of a {@link org.apache.http.config.Lookup} object that represents * Attribute name of a {@link org.apache.http.config.Lookup} object that represents
* the actual {@link CookieSpecProvider} registry. * the actual {@link org.apache.http.cookie.CookieSpecRegistry} registry.
*/ */
public static final String COOKIESPEC_REGISTRY = "http.cookiespec-registry"; public static final String COOKIESPEC_REGISTRY = "http.cookiespec-registry";
@ -119,16 +115,10 @@ public interface ClientContext {
/** /**
* Attribute name of a {@link org.apache.http.config.Lookup} object that represents * Attribute name of a {@link org.apache.http.config.Lookup} object that represents
* the actual {@link AuthSchemeProvider} registry. * the actual {@link org.apache.http.auth.AuthSchemeRegistry} registry.
*/ */
public static final String AUTHSCHEME_REGISTRY = "http.authscheme-registry"; public static final String AUTHSCHEME_REGISTRY = "http.authscheme-registry";
/**
* Attribute name of a {@link org.apache.http.config.Lookup} object that represents
* the actual {@link ConnectionSocketFactory} registry.
*
* @since 4.3
*/
public static final String SOCKET_FACTORY_REGISTRY = "http.socket-factory-registry"; public static final String SOCKET_FACTORY_REGISTRY = "http.socket-factory-registry";
/** /**

View File

@ -45,6 +45,7 @@ import org.apache.http.annotation.Immutable;
import org.apache.http.client.CookieStore; import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.Lookup; import org.apache.http.config.Lookup;
import org.apache.http.conn.routing.RouteInfo; import org.apache.http.conn.routing.RouteInfo;
import org.apache.http.cookie.Cookie; import org.apache.http.cookie.Cookie;
@ -122,10 +123,14 @@ public class RequestAddCookies implements HttpRequestInterceptor {
} }
URI requestURI = null; URI requestURI = null;
if (request instanceof HttpUriRequest) {
requestURI = ((HttpUriRequest) request).getURI();
} else {
try { try {
requestURI = new URI(request.getRequestLine().getUri()); requestURI = new URI(request.getRequestLine().getUri());
} catch (final URISyntaxException ignore) { } catch (final URISyntaxException ignore) {
} }
}
final String path = requestURI != null ? requestURI.getPath() : null; final String path = requestURI != null ? requestURI.getPath() : null;
final String hostName = targetHost.getHostName(); final String hostName = targetHost.getHostName();
int port = targetHost.getPort(); int port = targetHost.getPort();

View File

@ -36,7 +36,6 @@ import org.apache.http.auth.AUTH;
import org.apache.http.auth.AuthState; import org.apache.http.auth.AuthState;
import org.apache.http.conn.HttpRoutedConnection; import org.apache.http.conn.HttpRoutedConnection;
import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.client.HttpAuthenticator;
import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args; import org.apache.http.util.Args;
@ -47,7 +46,7 @@ import org.apache.http.util.Args;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link HttpAuthenticator}. * @deprecated (4.3) use {@link org.apache.http.impl.auth.HttpAuthenticator}.
*/ */
@Deprecated @Deprecated
@Immutable @Immutable

View File

@ -34,7 +34,6 @@ import org.apache.http.HttpRequest;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
import org.apache.http.auth.AUTH; import org.apache.http.auth.AUTH;
import org.apache.http.auth.AuthState; import org.apache.http.auth.AuthState;
import org.apache.http.impl.client.HttpAuthenticator;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args; import org.apache.http.util.Args;
@ -44,7 +43,7 @@ import org.apache.http.util.Args;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link HttpAuthenticator}. * @deprecated (4.3) use {@link org.apache.http.impl.auth.HttpAuthenticator}.
*/ */
@Deprecated @Deprecated
@Immutable @Immutable

View File

@ -39,7 +39,6 @@ import org.apache.http.annotation.Immutable;
import org.apache.http.auth.AuthScheme; import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthState; import org.apache.http.auth.AuthState;
import org.apache.http.client.AuthCache; import org.apache.http.client.AuthCache;
import org.apache.http.client.AuthenticationStrategy;
import org.apache.http.client.params.AuthPolicy; import org.apache.http.client.params.AuthPolicy;
import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SchemeRegistry;
@ -56,7 +55,7 @@ import org.apache.http.util.Args;
* *
* @since 4.1 * @since 4.1
* *
* @deprecated (4.2) use {@link AuthenticationStrategy} * @deprecated (4.2) use {@link org.apache.http.client.AuthenticationStrategy}
*/ */
@Immutable @Immutable
@Deprecated @Deprecated

View File

@ -49,7 +49,7 @@ public class CloneUtils {
} }
if (obj instanceof Cloneable) { if (obj instanceof Cloneable) {
final Class<?> clazz = obj.getClass (); final Class<?> clazz = obj.getClass ();
Method m; final Method m;
try { try {
m = clazz.getMethod("clone", (Class[]) null); m = clazz.getMethod("clone", (Class[]) null);
} catch (final NoSuchMethodException ex) { } catch (final NoSuchMethodException ex) {

View File

@ -28,7 +28,6 @@
package org.apache.http.client.utils; package org.apache.http.client.utils;
import java.lang.ref.SoftReference; import java.lang.ref.SoftReference;
import java.text.DateFormat;
import java.text.ParsePosition; import java.text.ParsePosition;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Calendar; import java.util.Calendar;
@ -125,31 +124,24 @@ public final class DateUtils {
* @return the parsed date or null if input could not be parsed * @return the parsed date or null if input could not be parsed
*/ */
public static Date parseDate( public static Date parseDate(
String dateValue, final String dateValue,
String[] dateFormats, final String[] dateFormats,
Date startDate final Date startDate) {
) {
Args.notNull(dateValue, "Date value"); Args.notNull(dateValue, "Date value");
if (dateFormats == null) { final String[] localDateFormats = dateFormats != null ? dateFormats : DEFAULT_PATTERNS;
dateFormats = DEFAULT_PATTERNS; final Date localStartDate = startDate != null ? startDate : DEFAULT_TWO_DIGIT_YEAR_START;
} String v = dateValue;
if (startDate == null) {
startDate = DEFAULT_TWO_DIGIT_YEAR_START;
}
// trim single quotes around date if present // trim single quotes around date if present
// see issue #5279 // see issue #5279
if (dateValue.length() > 1 if (v.length() > 1 && v.startsWith("'") && v.endsWith("'")) {
&& dateValue.startsWith("'") v = v.substring (1, v.length() - 1);
&& dateValue.endsWith("'")
) {
dateValue = dateValue.substring (1, dateValue.length() - 1);
} }
for (final String dateFormat : dateFormats) { for (final String dateFormat : localDateFormats) {
final SimpleDateFormat dateParser = DateFormatHolder.formatFor(dateFormat); final SimpleDateFormat dateParser = DateFormatHolder.formatFor(dateFormat);
dateParser.set2DigitYearStart(startDate); dateParser.set2DigitYearStart(localStartDate);
final ParsePosition pos = new ParsePosition(0); final ParsePosition pos = new ParsePosition(0);
final Date result = dateParser.parse(dateValue, pos); final Date result = dateParser.parse(v, pos);
if (pos.getIndex() != 0) { if (pos.getIndex() != 0) {
return result; return result;
} }
@ -190,7 +182,7 @@ public final class DateUtils {
} }
/** /**
* Clears thread-local variable containing {@link DateFormat} cache. * Clears thread-local variable containing {@link java.text.DateFormat} cache.
* *
* @since 4.3 * @since 4.3
*/ */

View File

@ -47,19 +47,20 @@ public class Rfc3492Idn implements Idn {
private static final char delimiter = '-'; private static final char delimiter = '-';
private static final String ACE_PREFIX = "xn--"; private static final String ACE_PREFIX = "xn--";
private int adapt(int delta, final int numpoints, final boolean firsttime) { private int adapt(final int delta, final int numpoints, final boolean firsttime) {
int d = delta;
if (firsttime) { if (firsttime) {
delta = delta / damp; d = d / damp;
} else { } else {
delta = delta / 2; d = d / 2;
} }
delta = delta + (delta / numpoints); d = d + (d / numpoints);
int k = 0; int k = 0;
while (delta > ((base - tmin) * tmax) / 2) { while (d > ((base - tmin) * tmax) / 2) {
delta = delta / (base - tmin); d = d / (base - tmin);
k = k + base; k = k + base;
} }
return k + (((base - tmin + 1) * delta) / (delta + skew)); return k + (((base - tmin + 1) * d) / (d + skew));
} }
private int digit(final char c) { private int digit(final char c) {
@ -91,7 +92,8 @@ public class Rfc3492Idn implements Idn {
return unicode.toString(); return unicode.toString();
} }
protected String decode(String input) { protected String decode(final String s) {
String input = s;
int n = initial_n; int n = initial_n;
int i = 0; int i = 0;
int bias = initial_bias; int bias = initial_bias;
@ -113,7 +115,7 @@ public class Rfc3492Idn implements Idn {
input = input.substring(1); input = input.substring(1);
final int digit = digit(c); final int digit = digit(c);
i = i + digit * w; // FIXME fail on overflow i = i + digit * w; // FIXME fail on overflow
int t; final int t;
if (k <= bias + tmin) { if (k <= bias + tmin) {
t = tmin; t = tmin;
} else if (k >= bias + tmax) { } else if (k >= bias + tmax) {

View File

@ -470,20 +470,21 @@ public class URIBuilder {
return buildString(); return buildString();
} }
private static String normalizePath(String path) { private static String normalizePath(final String path) {
if (path == null) { String s = path;
if (s == null) {
return null; return null;
} }
int n = 0; int n = 0;
for (; n < path.length(); n++) { for (; n < s.length(); n++) {
if (path.charAt(n) != '/') { if (s.charAt(n) != '/') {
break; break;
} }
} }
if (n > 1) { if (n > 1) {
path = path.substring(n - 1); s = s.substring(n - 1);
} }
return path; return s;
} }
} }

View File

@ -34,7 +34,6 @@ import java.util.Stack;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
import org.apache.http.client.URICollection;
import org.apache.http.util.Args; import org.apache.http.util.Args;
import org.apache.http.util.TextUtils; import org.apache.http.util.TextUtils;
@ -216,18 +215,19 @@ public class URIUtils {
* @param reference the URI reference * @param reference the URI reference
* @return the resulting URI * @return the resulting URI
*/ */
public static URI resolve(final URI baseURI, URI reference){ public static URI resolve(final URI baseURI, final URI reference){
Args.notNull(baseURI, "Base URI"); Args.notNull(baseURI, "Base URI");
Args.notNull(reference, "Reference URI"); Args.notNull(reference, "Reference URI");
final String s = reference.toString(); URI ref = reference;
final String s = ref.toString();
if (s.startsWith("?")) { if (s.startsWith("?")) {
return resolveReferenceStartingWithQueryString(baseURI, reference); return resolveReferenceStartingWithQueryString(baseURI, ref);
} }
final boolean emptyReference = s.length() == 0; final boolean emptyReference = s.length() == 0;
if (emptyReference) { if (emptyReference) {
reference = URI.create("#"); ref = URI.create("#");
} }
URI resolved = baseURI.resolve(reference); URI resolved = baseURI.resolve(ref);
if (emptyReference) { if (emptyReference) {
final String resolvedString = resolved.toString(); final String resolvedString = resolved.toString();
resolved = URI.create(resolvedString.substring(0, resolved = URI.create(resolvedString.substring(0,

View File

@ -29,18 +29,17 @@ package org.apache.http.conn;
import java.io.IOException; import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.Socket;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.conn.scheme.SchemeSocketFactory;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
/** /**
* ClientConnectionOperator represents a strategy for creating * ClientConnectionOperator represents a strategy for creating
* {@link OperatedClientConnection} instances and updating the underlying * {@link OperatedClientConnection} instances and updating the underlying
* {@link Socket} of those objects. Implementations will most likely make use * {@link java.net.Socket} of those objects. Implementations will most
* of {@link SchemeSocketFactory}s to create {@link Socket} instances. * likely make use of {@link org.apache.http.conn.scheme.SchemeSocketFactory}s
* to create {@link java.net.Socket} instances.
* <p> * <p>
* The methods in this interface allow the creation of plain and layered * The methods in this interface allow the creation of plain and layered
* sockets. Creating a tunnelled connection through a proxy, however, * sockets. Creating a tunnelled connection through a proxy, however,

View File

@ -30,7 +30,6 @@ package org.apache.http.conn;
import java.io.IOException; import java.io.IOException;
import java.io.InterruptedIOException; import java.io.InterruptedIOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Arrays; import java.util.Arrays;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;

View File

@ -26,7 +26,6 @@
*/ */
package org.apache.http.conn; package org.apache.http.conn;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
@ -48,10 +47,11 @@ public interface ConnectionKeepAliveStrategy {
* it MUST not reused. A value of 0 or less may be returned to indicate that * it MUST not reused. A value of 0 or less may be returned to indicate that
* there is no suitable suggestion. * there is no suitable suggestion.
* *
* When coupled with a {@link ConnectionReuseStrategy}, if * When coupled with a {@link org.apache.http.ConnectionReuseStrategy}, if
* {@link ConnectionReuseStrategy#keepAlive(HttpResponse, HttpContext)} * {@link org.apache.http.ConnectionReuseStrategy#keepAlive(
* returns true, this allows you to control how long the reuse will last. If * HttpResponse, HttpContext)} returns true, this allows you to control
* keepAlive returns false, this should have no meaningful impact * how long the reuse will last. If keepAlive returns false, this should
* have no meaningful impact
* *
* @param response * @param response
* The last response received over the connection. * The last response received over the connection.

View File

@ -29,7 +29,6 @@ package org.apache.http.conn;
import java.io.IOException; import java.io.IOException;
import java.net.ConnectException; import java.net.ConnectException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Arrays; import java.util.Arrays;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;

View File

@ -38,7 +38,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
import org.apache.http.conn.scheme.SchemeSocketFactory;
import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
@ -55,7 +54,7 @@ import org.apache.http.util.Asserts;
* @since 4.0 * @since 4.0
* *
* @deprecated (4.1) Do not use. For multihome support socket factories must implement * @deprecated (4.1) Do not use. For multihome support socket factories must implement
* {@link SchemeSocketFactory} interface. * {@link org.apache.http.conn.scheme.SchemeSocketFactory} interface.
*/ */
@Deprecated @Deprecated
@Immutable @Immutable
@ -93,7 +92,7 @@ public final class MultihomePlainSocketFactory implements SocketFactory {
* given host name resolves to. If connection to all addresses fail, the * given host name resolves to. If connection to all addresses fail, the
* last I/O exception is propagated to the caller. * last I/O exception is propagated to the caller.
* *
* @param sock socket to connect to any of the given addresses * @param socket socket to connect to any of the given addresses
* @param host Host name to connect to * @param host Host name to connect to
* @param port the port to connect to * @param port the port to connect to
* @param localAddress local address * @param localAddress local address
@ -103,27 +102,21 @@ public final class MultihomePlainSocketFactory implements SocketFactory {
* @throws IOException if an error occurs during the connection * @throws IOException if an error occurs during the connection
* @throws SocketTimeoutException if timeout expires before connecting * @throws SocketTimeoutException if timeout expires before connecting
*/ */
public Socket connectSocket(Socket sock, final String host, final int port, public Socket connectSocket(final Socket socket, final String host, final int port,
final InetAddress localAddress, int localPort, final InetAddress localAddress, final int localPort,
final HttpParams params) final HttpParams params)
throws IOException { throws IOException {
Args.notNull(host, "Target host"); Args.notNull(host, "Target host");
Args.notNull(params, "HTTP parameters"); Args.notNull(params, "HTTP parameters");
Socket sock = socket;
if (sock == null) { if (sock == null) {
sock = createSocket(); sock = createSocket();
} }
if ((localAddress != null) || (localPort > 0)) { if ((localAddress != null) || (localPort > 0)) {
final InetSocketAddress isa = new InetSocketAddress(localAddress,
// we need to bind explicitly localPort > 0 ? localPort : 0);
if (localPort < 0)
{
localPort = 0; // indicates "any"
}
final InetSocketAddress isa =
new InetSocketAddress(localAddress, localPort);
sock.bind(isa); sock.bind(isa);
} }

View File

@ -26,14 +26,13 @@
*/ */
package org.apache.http.conn.params; package org.apache.http.conn.params;
import org.apache.http.impl.conn.DefaultHttpResponseParser;
/** /**
* Parameter names for HTTP client connections. * Parameter names for HTTP client connections.
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.1) use custom {@link DefaultHttpResponseParser} implementation. * @deprecated (4.1) use custom {@link
* org.apache.http.impl.conn.DefaultHttpResponseParser} implementation.
*/ */
@Deprecated @Deprecated
public interface ConnConnectionPNames { public interface ConnConnectionPNames {
@ -55,7 +54,8 @@ public interface ConnConnectionPNames {
* Use {@link java.lang.Integer#MAX_VALUE} for unlimited number. * Use {@link java.lang.Integer#MAX_VALUE} for unlimited number.
* </p> * </p>
* *
* @deprecated (4.1) Use custom {@link DefaultHttpResponseParser} implementation * @deprecated (4.1) Use custom {@link
* org.apache.http.impl.conn.DefaultHttpResponseParser} implementation
*/ */
@Deprecated @Deprecated
public static final String MAX_STATUS_LINE_GARBAGE = "http.connection.max-status-line-garbage"; public static final String MAX_STATUS_LINE_GARBAGE = "http.connection.max-status-line-garbage";

View File

@ -27,7 +27,6 @@
package org.apache.http.conn.params; package org.apache.http.conn.params;
import org.apache.http.impl.conn.DefaultHttpResponseParser;
import org.apache.http.params.HttpAbstractParamBean; import org.apache.http.params.HttpAbstractParamBean;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
@ -38,7 +37,8 @@ import org.apache.http.params.HttpParams;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.2) do not use * @deprecated (4.1) use custom {@link
* org.apache.http.impl.conn.DefaultHttpResponseParser} implementation.
*/ */
@Deprecated @Deprecated
public class ConnConnectionParamBean extends HttpAbstractParamBean { public class ConnConnectionParamBean extends HttpAbstractParamBean {
@ -48,7 +48,8 @@ public class ConnConnectionParamBean extends HttpAbstractParamBean {
} }
/** /**
* @deprecated (4.2) Use custom {@link DefaultHttpResponseParser} implementation * @deprecated (4.2) Use custom {@link
* org.apache.http.impl.conn.DefaultHttpResponseParser} implementation
*/ */
@Deprecated @Deprecated
public void setMaxStatusLineGarbage (final int maxStatusLineGarbage) { public void setMaxStatusLineGarbage (final int maxStatusLineGarbage) {

View File

@ -28,7 +28,6 @@ package org.apache.http.conn.params;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.util.Args; import org.apache.http.util.Args;
@ -56,7 +55,8 @@ public final class ConnManagerParams implements ConnManagerPNames {
* *
* @return timeout in milliseconds. * @return timeout in milliseconds.
* *
* @deprecated (4.1) use {@link HttpConnectionParams#getConnectionTimeout(HttpParams)} * @deprecated (4.1) use {@link
* org.apache.http.params.HttpConnectionParams#getConnectionTimeout(HttpParams)}
*/ */
@Deprecated @Deprecated
public static long getTimeout(final HttpParams params) { public static long getTimeout(final HttpParams params) {
@ -71,7 +71,8 @@ public final class ConnManagerParams implements ConnManagerPNames {
* *
* @param timeout the timeout in milliseconds * @param timeout the timeout in milliseconds
* *
* @deprecated (4.1) use {@link HttpConnectionParams#setConnectionTimeout(HttpParams, int)} * @deprecated (4.1) use {@link
* org.apache.http.params.HttpConnectionParams#setConnectionTimeout(HttpParams, int)}
*/ */
@Deprecated @Deprecated
public static void setTimeout(final HttpParams params, final long timeout) { public static void setTimeout(final HttpParams params, final long timeout) {

View File

@ -31,7 +31,6 @@ import java.util.concurrent.ConcurrentHashMap;
import org.apache.http.annotation.ThreadSafe; import org.apache.http.annotation.ThreadSafe;
import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.pool.ConnPoolControl;
import org.apache.http.util.Args; import org.apache.http.util.Args;
/** /**
@ -42,7 +41,7 @@ import org.apache.http.util.Args;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.2) use {@link ConnPoolControl} * @deprecated (4.2) use {@link org.apache.http.pool.ConnPoolControl}
*/ */
@Deprecated @Deprecated
@ThreadSafe @ThreadSafe

View File

@ -26,14 +26,12 @@
*/ */
package org.apache.http.conn.params; package org.apache.http.conn.params;
import org.apache.http.client.config.RequestConfig;
/** /**
* Parameter names for connection routing. * Parameter names for connection routing.
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link RequestConfig}. * @deprecated (4.3) use {@link org.apache.http.client.config.RequestConfig}.
*/ */
@Deprecated @Deprecated
public interface ConnRoutePNames { public interface ConnRoutePNames {

View File

@ -31,7 +31,6 @@ import java.net.InetAddress;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.annotation.NotThreadSafe; import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.params.HttpAbstractParamBean; import org.apache.http.params.HttpAbstractParamBean;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
@ -43,7 +42,7 @@ import org.apache.http.params.HttpParams;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link RequestConfig}. * @deprecated (4.3) use {@link org.apache.http.client.config.RequestConfig}.
*/ */
@Deprecated @Deprecated
@NotThreadSafe @NotThreadSafe

View File

@ -30,7 +30,6 @@ import java.net.InetAddress;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.util.Args; import org.apache.http.util.Args;
@ -41,7 +40,7 @@ import org.apache.http.util.Args;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link RequestConfig}. * @deprecated (4.3) use {@link org.apache.http.client.config.RequestConfig}.
*/ */
@Deprecated @Deprecated
@Immutable @Immutable

View File

@ -92,7 +92,7 @@ public final class HttpRoute implements RouteInfo, Cloneable {
private HttpRoute(final InetAddress local, private HttpRoute(final InetAddress local,
final HttpHost target, final HttpHost[] proxies, final HttpHost target, final HttpHost[] proxies,
final boolean secure, final boolean secure,
TunnelType tunnelled, LayerType layered) { final TunnelType tunnelled, final LayerType layered) {
Args.notNull(target, "Target host"); Args.notNull(target, "Target host");
Args.notNull(proxies, "Array of proxy hosts"); Args.notNull(proxies, "Array of proxy hosts");
for (final HttpHost proxy: proxies) { for (final HttpHost proxy: proxies) {
@ -101,23 +101,14 @@ public final class HttpRoute implements RouteInfo, Cloneable {
if (tunnelled == TunnelType.TUNNELLED) { if (tunnelled == TunnelType.TUNNELLED) {
Args.check(proxies.length > 0, "Proxy required if tunnelled"); Args.check(proxies.length > 0, "Proxy required if tunnelled");
} }
// tunnelled is already checked above, that is in line with the default
if (tunnelled == null) {
tunnelled = TunnelType.PLAIN;
}
if (layered == null) {
layered = LayerType.PLAIN;
}
this.targetHost = target; this.targetHost = target;
this.localAddress = local; this.localAddress = local;
this.proxyChain = proxies; this.proxyChain = proxies;
this.secure = secure; this.secure = secure;
this.tunnelled = tunnelled; this.tunnelled = tunnelled != null ? tunnelled : TunnelType.PLAIN;
this.layered = layered; this.layered = layered != null ? layered : LayerType.PLAIN;
} }
/** /**
* Creates a new route with all attributes specified explicitly. * Creates a new route with all attributes specified explicitly.
* *

View File

@ -36,7 +36,6 @@ import java.net.UnknownHostException;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.DnsResolver;
import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.util.Args; import org.apache.http.util.Args;
@ -64,7 +63,7 @@ public class PlainSocketFactory implements SocketFactory, SchemeSocketFactory {
} }
/** /**
* @deprecated (4.1) use {@link DnsResolver} * @deprecated (4.1) use {@link org.apache.http.conn.DnsResolver}
*/ */
@Deprecated @Deprecated
public PlainSocketFactory(final HostNameResolver nameResolver) { public PlainSocketFactory(final HostNameResolver nameResolver) {
@ -142,17 +141,13 @@ public class PlainSocketFactory implements SocketFactory, SchemeSocketFactory {
public Socket connectSocket( public Socket connectSocket(
final Socket socket, final Socket socket,
final String host, final int port, final String host, final int port,
final InetAddress localAddress, int localPort, final InetAddress localAddress, final int localPort,
final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
InetSocketAddress local = null; InetSocketAddress local = null;
if (localAddress != null || localPort > 0) { if (localAddress != null || localPort > 0) {
// we need to bind explicitly local = new InetSocketAddress(localAddress, localPort > 0 ? localPort : 0);
if (localPort < 0) {
localPort = 0; // indicates "any"
} }
local = new InetSocketAddress(localAddress, localPort); final InetAddress remoteAddress;
}
InetAddress remoteAddress;
if (this.nameResolver != null) { if (this.nameResolver != null) {
remoteAddress = this.nameResolver.resolve(host); remoteAddress = this.nameResolver.resolve(host);
} else { } else {

View File

@ -29,8 +29,6 @@ package org.apache.http.conn.scheme;
import java.util.Locale; import java.util.Locale;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
import org.apache.http.config.Registry;
import org.apache.http.conn.SchemePortResolver;
import org.apache.http.util.Args; import org.apache.http.util.Args;
import org.apache.http.util.LangUtils; import org.apache.http.util.LangUtils;
@ -48,8 +46,8 @@ import org.apache.http.util.LangUtils;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link SchemePortResolver} for default port resolution * @deprecated (4.3) use {@link org.apache.http.conn.SchemePortResolver} for default port
* and {@link Registry} for socket factory lookups. * resolution and {@link org.apache.http.config.Registry} for socket factory lookups.
*/ */
@Immutable @Immutable
@Deprecated @Deprecated

View File

@ -31,7 +31,6 @@ import java.io.IOException;
import java.net.Socket; import java.net.Socket;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
/** /**
@ -39,7 +38,8 @@ import org.apache.http.params.HttpParams;
* *
* @since 4.2 * @since 4.2
* *
* @deprecated (4.3) use {@link LayeredConnectionSocketFactory} * @deprecated (4.3) use {@link
* org.apache.http.conn.socket.LayeredConnectionSocketFactory}
*/ */
@Deprecated @Deprecated
public interface SchemeLayeredSocketFactory extends SchemeSocketFactory { public interface SchemeLayeredSocketFactory extends SchemeSocketFactory {

View File

@ -33,7 +33,6 @@ import java.util.concurrent.ConcurrentHashMap;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.annotation.ThreadSafe; import org.apache.http.annotation.ThreadSafe;
import org.apache.http.config.Registry;
import org.apache.http.util.Args; import org.apache.http.util.Args;
/** /**
@ -42,7 +41,7 @@ import org.apache.http.util.Args;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link Registry} * @deprecated (4.3) use {@link org.apache.http.config.Registry}
*/ */
@ThreadSafe @ThreadSafe
@Deprecated @Deprecated

View File

@ -32,10 +32,7 @@ import java.net.InetSocketAddress;
import java.net.Socket; import java.net.Socket;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import org.apache.http.HttpHost;
import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpInetSocketAddress;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
/** /**
@ -44,7 +41,7 @@ import org.apache.http.params.HttpParams;
* *
* @since 4.1 * @since 4.1
* *
* @deprecated (4.3) use {@link ConnectionSocketFactory} * @deprecated (4.3) use {@link org.apache.http.conn.socket.ConnectionSocketFactory}
*/ */
@Deprecated @Deprecated
public interface SchemeSocketFactory { public interface SchemeSocketFactory {
@ -70,10 +67,12 @@ public interface SchemeSocketFactory {
/** /**
* Connects a socket to the target host with the given remote address. * Connects a socket to the target host with the given remote address.
* <p/> * <p/>
* Please note that {@link HttpInetSocketAddress} class should be used in order to pass * Please note that {@link org.apache.http.conn.HttpInetSocketAddress} class should
* the target remote address along with the original {@link HttpHost} value used to resolve * be used in order to pass the target remote address along with the original
* the address. The use of {@link HttpInetSocketAddress} can also ensure that no reverse * {@link org.apache.http.HttpHost} value used to resolve the address. The use of
* DNS lookup will be performed if the target remote address was specified as an IP address. * {@link org.apache.http.conn.HttpInetSocketAddress} can also ensure that no reverse
* DNS lookup will be performed if the target remote address was specified
* as an IP address.
* *
* @param sock the socket to connect, as obtained from * @param sock the socket to connect, as obtained from
* {@link #createSocket(HttpParams) createSocket}. * {@link #createSocket(HttpParams) createSocket}.
@ -94,7 +93,7 @@ public interface SchemeSocketFactory {
* @throws ConnectTimeoutException if the socket cannot be connected * @throws ConnectTimeoutException if the socket cannot be connected
* within the time limit defined in the <code>params</code> * within the time limit defined in the <code>params</code>
* *
* @see HttpInetSocketAddress * @see org.apache.http.conn.HttpInetSocketAddress
*/ */
Socket connectSocket( Socket connectSocket(
Socket sock, Socket sock,

View File

@ -37,9 +37,6 @@ import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.params.BasicHttpParams; import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
/**
* @deprecated (4.1) do not use
*/
@Deprecated @Deprecated
class SocketFactoryAdaptor implements SocketFactory { class SocketFactoryAdaptor implements SocketFactory {
@ -58,15 +55,11 @@ class SocketFactoryAdaptor implements SocketFactory {
public Socket connectSocket( public Socket connectSocket(
final Socket socket, final Socket socket,
final String host, final int port, final String host, final int port,
final InetAddress localAddress, int localPort, final InetAddress localAddress, final int localPort,
final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
InetSocketAddress local = null; InetSocketAddress local = null;
if (localAddress != null || localPort > 0) { if (localAddress != null || localPort > 0) {
// we need to bind explicitly local = new InetSocketAddress(localAddress, localPort > 0 ? localPort : 0);
if (localPort < 0) {
localPort = 0; // indicates "any"
}
local = new InetSocketAddress(localAddress, localPort);
} }
final InetAddress remoteAddress = InetAddress.getByName(host); final InetAddress remoteAddress = InetAddress.getByName(host);
final InetSocketAddress remote = new InetSocketAddress(remoteAddress, port); final InetSocketAddress remote = new InetSocketAddress(remoteAddress, port);

View File

@ -295,7 +295,7 @@ public abstract class AbstractVerifier implements X509HostnameVerifier {
*/ */
private static String[] getSubjectAlts( private static String[] getSubjectAlts(
final X509Certificate cert, final String hostname) { final X509Certificate cert, final String hostname) {
int subjectType; final int subjectType;
if (isIPAddress(hostname)) { if (isIPAddress(hostname)) {
subjectType = 7; subjectType = 7;
} else { } else {
@ -375,7 +375,7 @@ public abstract class AbstractVerifier implements X509HostnameVerifier {
return hostname; return hostname;
} }
try { try {
InetAddress inetAddress = InetAddress.getByName(hostname); final InetAddress inetAddress = InetAddress.getByName(hostname);
return inetAddress.getHostAddress(); return inetAddress.getHostAddress();
} catch (UnknownHostException uhe) { // Should not happen, because we check for IPv6 address above } catch (UnknownHostException uhe) { // Should not happen, because we check for IPv6 address above
log.error("Unexpected error converting "+hostname, uhe); log.error("Unexpected error converting "+hostname, uhe);

View File

@ -49,7 +49,7 @@ public class SSLContexts {
* *
* @return the default SSL socket factory * @return the default SSL socket factory
*/ */
public static final SSLContext createDefault() throws SSLInitializationException { public static SSLContext createDefault() throws SSLInitializationException {
try { try {
final SSLContext sslcontext = SSLContext.getInstance(SSLContextBuilder.TLS); final SSLContext sslcontext = SSLContext.getInstance(SSLContextBuilder.TLS);
sslcontext.init(null, null, null); sslcontext.init(null, null, null);
@ -70,7 +70,7 @@ public class SSLContexts {
* *
* @return default system SSL context * @return default system SSL context
*/ */
public static final SSLContext createSystemDefault() throws SSLInitializationException { public static SSLContext createSystemDefault() throws SSLInitializationException {
try { try {
return SSLContext.getInstance("Default"); return SSLContext.getInstance("Default");
} catch (final NoSuchAlgorithmException ex) { } catch (final NoSuchAlgorithmException ex) {
@ -83,7 +83,7 @@ public class SSLContexts {
* *
* @return default system SSL context * @return default system SSL context
*/ */
public static final SSLContextBuilder custom() { public static SSLContextBuilder custom() {
return new SSLContextBuilder(); return new SSLContextBuilder();
} }

View File

@ -28,11 +28,9 @@
package org.apache.http.conn.ssl; package org.apache.http.conn.ssl;
import java.io.IOException; import java.io.IOException;
import java.net.ConnectException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.Socket; import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.KeyStore; import java.security.KeyStore;
@ -166,6 +164,7 @@ public class SSLSocketFactory implements LayeredConnectionSocketFactory, SchemeL
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
this(SSLContexts.custom() this(SSLContexts.custom()
.useProtocol(algorithm) .useProtocol(algorithm)
.setSecureRandom(random)
.loadKeyMaterial(keystore, keyPassword != null ? keyPassword.toCharArray() : null) .loadKeyMaterial(keystore, keyPassword != null ? keyPassword.toCharArray() : null)
.loadTrustMaterial(truststore) .loadTrustMaterial(truststore)
.build(), .build(),
@ -190,6 +189,7 @@ public class SSLSocketFactory implements LayeredConnectionSocketFactory, SchemeL
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
this(SSLContexts.custom() this(SSLContexts.custom()
.useProtocol(algorithm) .useProtocol(algorithm)
.setSecureRandom(random)
.loadKeyMaterial(keystore, keyPassword != null ? keyPassword.toCharArray() : null) .loadKeyMaterial(keystore, keyPassword != null ? keyPassword.toCharArray() : null)
.loadTrustMaterial(truststore, trustStrategy) .loadTrustMaterial(truststore, trustStrategy)
.build(), .build(),
@ -213,6 +213,7 @@ public class SSLSocketFactory implements LayeredConnectionSocketFactory, SchemeL
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
this(SSLContexts.custom() this(SSLContexts.custom()
.useProtocol(algorithm) .useProtocol(algorithm)
.setSecureRandom(random)
.loadKeyMaterial(keystore, keyPassword != null ? keyPassword.toCharArray() : null) .loadKeyMaterial(keystore, keyPassword != null ? keyPassword.toCharArray() : null)
.loadTrustMaterial(truststore) .loadTrustMaterial(truststore)
.build(), .build(),
@ -392,7 +393,7 @@ public class SSLSocketFactory implements LayeredConnectionSocketFactory, SchemeL
final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
Args.notNull(remoteAddress, "Remote address"); Args.notNull(remoteAddress, "Remote address");
Args.notNull(params, "HTTP parameters"); Args.notNull(params, "HTTP parameters");
HttpHost host; final HttpHost host;
if (remoteAddress instanceof HttpInetSocketAddress) { if (remoteAddress instanceof HttpInetSocketAddress) {
host = ((HttpInetSocketAddress) remoteAddress).getHttpHost(); host = ((HttpInetSocketAddress) remoteAddress).getHttpHost();
} else { } else {
@ -473,9 +474,9 @@ public class SSLSocketFactory implements LayeredConnectionSocketFactory, SchemeL
public Socket connectSocket( public Socket connectSocket(
final Socket socket, final Socket socket,
final String host, final int port, final String host, final int port,
final InetAddress local, int localPort, final InetAddress local, final int localPort,
final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
InetAddress remote; final InetAddress remote;
if (this.nameResolver != null) { if (this.nameResolver != null) {
remote = this.nameResolver.resolve(host); remote = this.nameResolver.resolve(host);
} else { } else {
@ -483,11 +484,7 @@ public class SSLSocketFactory implements LayeredConnectionSocketFactory, SchemeL
} }
InetSocketAddress localAddress = null; InetSocketAddress localAddress = null;
if (local != null || localPort > 0) { if (local != null || localPort > 0) {
// we need to bind explicitly localAddress = new InetSocketAddress(local, localPort > 0 ? localPort : 0);
if (localPort < 0) {
localPort = 0; // indicates "any"
}
localAddress = new InetSocketAddress(local, localPort);
} }
final InetSocketAddress remoteAddress = new HttpInetSocketAddress( final InetSocketAddress remoteAddress = new HttpInetSocketAddress(
new HttpHost(host, port), remote, port); new HttpHost(host, port), remote, port);

View File

@ -36,7 +36,6 @@ import java.util.concurrent.ConcurrentHashMap;
import org.apache.http.HttpRequest; import org.apache.http.HttpRequest;
import org.apache.http.annotation.ThreadSafe; import org.apache.http.annotation.ThreadSafe;
import org.apache.http.config.Lookup; import org.apache.http.config.Lookup;
import org.apache.http.config.Registry;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
@ -49,7 +48,7 @@ import org.apache.http.util.Args;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link Registry}. * @deprecated (4.3) use {@link org.apache.http.config.Registry}.
*/ */
@ThreadSafe @ThreadSafe
@Deprecated @Deprecated

View File

@ -27,14 +27,13 @@
package org.apache.http.cookie.params; package org.apache.http.cookie.params;
import org.apache.http.cookie.CookieSpecProvider;
/** /**
* Parameter names for HTTP cookie management classes. * Parameter names for HTTP cookie management classes.
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use constructor parameters of {@link CookieSpecProvider}s. * @deprecated (4.3) use constructor parameters of {@link
* org.apache.http.cookie.CookieSpecProvider}s.
*/ */
@Deprecated @Deprecated
public interface CookieSpecPNames { public interface CookieSpecPNames {

View File

@ -30,7 +30,6 @@ package org.apache.http.cookie.params;
import java.util.Collection; import java.util.Collection;
import org.apache.http.annotation.NotThreadSafe; import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.params.HttpAbstractParamBean; import org.apache.http.params.HttpAbstractParamBean;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
@ -41,7 +40,8 @@ import org.apache.http.params.HttpParams;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use constructor parameters of {@link CookieSpecProvider}s. * @deprecated (4.3) use constructor parameters of {@link
* org.apache.http.cookie.CookieSpecProvider}s.
*/ */
@Deprecated @Deprecated
@NotThreadSafe @NotThreadSafe

View File

@ -97,7 +97,7 @@ public abstract class AuthSchemeBase implements ContextAwareAuthScheme {
throw new MalformedChallengeException("Unexpected header name: " + authheader); throw new MalformedChallengeException("Unexpected header name: " + authheader);
} }
CharArrayBuffer buffer; final CharArrayBuffer buffer;
int pos; int pos;
if (header instanceof FormattedHeader) { if (header instanceof FormattedHeader) {
buffer = ((FormattedHeader) header).getBuffer(); buffer = ((FormattedHeader) header).getBuffer();

View File

@ -36,9 +36,7 @@ import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.auth.AUTH; import org.apache.http.auth.AUTH;
import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.ChallengeState; import org.apache.http.auth.ChallengeState;
import org.apache.http.auth.ContextAwareAuthScheme;
import org.apache.http.auth.Credentials; import org.apache.http.auth.Credentials;
import org.apache.http.auth.InvalidCredentialsException;
import org.apache.http.auth.MalformedChallengeException; import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.message.BufferedHeader; import org.apache.http.message.BufferedHeader;
import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpContext;
@ -130,7 +128,8 @@ public class BasicScheme extends RFC2617Scheme {
} }
/** /**
* @deprecated (4.2) Use {@link ContextAwareAuthScheme#authenticate(Credentials, HttpRequest, org.apache.http.protocol.HttpContext)} * @deprecated (4.2) Use {@link org.apache.http.auth.ContextAwareAuthScheme#authenticate(
* Credentials, HttpRequest, org.apache.http.protocol.HttpContext)}
*/ */
@Deprecated @Deprecated
public Header authenticate( public Header authenticate(
@ -143,8 +142,8 @@ public class BasicScheme extends RFC2617Scheme {
* *
* @param credentials The set of credentials to be used for authentication * @param credentials The set of credentials to be used for authentication
* @param request The request being authenticated * @param request The request being authenticated
* @throws InvalidCredentialsException if authentication credentials are not * @throws org.apache.http.auth.InvalidCredentialsException if authentication
* valid or not applicable for this authentication scheme * credentials are not valid or not applicable for this authentication scheme
* @throws AuthenticationException if authorization string cannot * @throws AuthenticationException if authorization string cannot
* be generated due to an authentication failure * be generated due to an authentication failure
* *

View File

@ -47,7 +47,6 @@ import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.auth.AUTH; import org.apache.http.auth.AUTH;
import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.ChallengeState; import org.apache.http.auth.ChallengeState;
import org.apache.http.auth.ContextAwareAuthScheme;
import org.apache.http.auth.Credentials; import org.apache.http.auth.Credentials;
import org.apache.http.auth.MalformedChallengeException; import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.message.BasicHeaderValueFormatter; import org.apache.http.message.BasicHeaderValueFormatter;
@ -178,7 +177,8 @@ public class DigestScheme extends RFC2617Scheme {
} }
/** /**
* @deprecated (4.2) Use {@link ContextAwareAuthScheme#authenticate(Credentials, HttpRequest, org.apache.http.protocol.HttpContext)} * @deprecated (4.2) Use {@link org.apache.http.auth.ContextAwareAuthScheme#authenticate(
* Credentials, HttpRequest, org.apache.http.protocol.HttpContext)}
*/ */
@Deprecated @Deprecated
public Header authenticate( public Header authenticate(
@ -288,7 +288,7 @@ public class DigestScheme extends RFC2617Scheme {
digAlg = "MD5"; digAlg = "MD5";
} }
MessageDigest digester; final MessageDigest digester;
try { try {
digester = createMessageDigest(digAlg); digester = createMessageDigest(digAlg);
} catch (final UnsupportedDigestAlgorithmException ex) { } catch (final UnsupportedDigestAlgorithmException ex) {
@ -377,7 +377,7 @@ public class DigestScheme extends RFC2617Scheme {
// 3.2.2.1 // 3.2.2.1
String digestValue; final String digestValue;
if (qop == QOP_MISSING) { if (qop == QOP_MISSING) {
sb.setLength(0); sb.setLength(0);
sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2); sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2);

View File

@ -34,7 +34,6 @@ import org.apache.http.HttpHost;
import org.apache.http.HttpRequest; import org.apache.http.HttpRequest;
import org.apache.http.auth.AUTH; import org.apache.http.auth.AUTH;
import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.ContextAwareAuthScheme;
import org.apache.http.auth.Credentials; import org.apache.http.auth.Credentials;
import org.apache.http.auth.InvalidCredentialsException; import org.apache.http.auth.InvalidCredentialsException;
import org.apache.http.auth.MalformedChallengeException; import org.apache.http.auth.MalformedChallengeException;
@ -111,7 +110,8 @@ public abstract class GGSSchemeBase extends AuthSchemeBase {
} }
/** /**
* @deprecated (4.2) Use {@link ContextAwareAuthScheme#authenticate(Credentials, HttpRequest, org.apache.http.protocol.HttpContext)} * @deprecated (4.2) Use {@link org.apache.http.auth.ContextAwareAuthScheme#authenticate(
* Credentials, HttpRequest, org.apache.http.protocol.HttpContext)}
*/ */
@Deprecated @Deprecated
public Header authenticate( public Header authenticate(
@ -146,7 +146,7 @@ public abstract class GGSSchemeBase extends AuthSchemeBase {
} else { } else {
host = route.getTargetHost(); host = route.getTargetHost();
} }
String authServer; final String authServer;
if (!this.stripPort && host.getPort() > 0) { if (!this.stripPort && host.getPort() > 0) {
authServer = host.toHostString(); authServer = host.toHostString();
} else { } else {

View File

@ -72,7 +72,7 @@ final class NTLMEngineImpl implements NTLMEngine {
java.security.SecureRandom rnd = null; java.security.SecureRandom rnd = null;
try { try {
rnd = java.security.SecureRandom.getInstance("SHA1PRNG"); rnd = java.security.SecureRandom.getInstance("SHA1PRNG");
} catch (Exception e) { } catch (Exception ignore) {
} }
RND_GEN = rnd; RND_GEN = rnd;
} }
@ -84,10 +84,10 @@ final class NTLMEngineImpl implements NTLMEngine {
private String credentialCharset = DEFAULT_CHARSET; private String credentialCharset = DEFAULT_CHARSET;
/** The signature string as bytes in the default encoding */ /** The signature string as bytes in the default encoding */
private static byte[] SIGNATURE; private static final byte[] SIGNATURE;
static { static {
byte[] bytesWithoutNull = EncodingUtils.getBytes("NTLMSSP", "ASCII"); final byte[] bytesWithoutNull = EncodingUtils.getBytes("NTLMSSP", "ASCII");
SIGNATURE = new byte[bytesWithoutNull.length + 1]; SIGNATURE = new byte[bytesWithoutNull.length + 1];
System.arraycopy(bytesWithoutNull, 0, SIGNATURE, 0, bytesWithoutNull.length); System.arraycopy(bytesWithoutNull, 0, SIGNATURE, 0, bytesWithoutNull.length);
SIGNATURE[bytesWithoutNull.length] = (byte) 0x00; SIGNATURE[bytesWithoutNull.length] = (byte) 0x00;
@ -107,17 +107,17 @@ final class NTLMEngineImpl implements NTLMEngine {
* @param domain * @param domain
* the NT domain to authenticate in. * the NT domain to authenticate in.
* @return The response. * @return The response.
* @throws HttpException * @throws org.apache.http.HttpException
* If the messages cannot be retrieved. * If the messages cannot be retrieved.
*/ */
final String getResponseFor(String message, String username, String password, final String getResponseFor(final String message, final String username, final String password,
String host, String domain) throws NTLMEngineException { final String host, final String domain) throws NTLMEngineException {
final String response; final String response;
if (message == null || message.trim().equals("")) { if (message == null || message.trim().equals("")) {
response = getType1Message(host, domain); response = getType1Message(host, domain);
} else { } else {
Type2Message t2m = new Type2Message(message); final Type2Message t2m = new Type2Message(message);
response = getType3Message(username, password, host, domain, t2m.getChallenge(), t2m response = getType3Message(username, password, host, domain, t2m.getChallenge(), t2m
.getFlags(), t2m.getTarget(), t2m.getTargetInfo()); .getFlags(), t2m.getTarget(), t2m.getTargetInfo());
} }
@ -135,7 +135,7 @@ final class NTLMEngineImpl implements NTLMEngine {
* The domain to authenticate with. * The domain to authenticate with.
* @return String the message to add to the HTTP request header. * @return String the message to add to the HTTP request header.
*/ */
String getType1Message(String host, String domain) throws NTLMEngineException { String getType1Message(final String host, final String domain) throws NTLMEngineException {
return new Type1Message(domain, host).getResponse(); return new Type1Message(domain, host).getResponse();
} }
@ -159,8 +159,8 @@ final class NTLMEngineImpl implements NTLMEngine {
* @throws NTLMEngineException * @throws NTLMEngineException
* If {@encrypt(byte[],byte[])} fails. * If {@encrypt(byte[],byte[])} fails.
*/ */
String getType3Message(String user, String password, String host, String domain, String getType3Message(final String user, final String password, final String host, final String domain,
byte[] nonce, int type2Flags, String target, byte[] targetInformation) final byte[] nonce, final int type2Flags, final String target, final byte[] targetInformation)
throws NTLMEngineException { throws NTLMEngineException {
return new Type3Message(domain, host, user, password, nonce, type2Flags, target, return new Type3Message(domain, host, user, password, nonce, type2Flags, target,
targetInformation).getResponse(); targetInformation).getResponse();
@ -177,48 +177,48 @@ final class NTLMEngineImpl implements NTLMEngine {
* @param credentialCharset * @param credentialCharset
* The credentialCharset to set. * The credentialCharset to set.
*/ */
void setCredentialCharset(String credentialCharset) { void setCredentialCharset(final String credentialCharset) {
this.credentialCharset = credentialCharset; this.credentialCharset = credentialCharset;
} }
/** Strip dot suffix from a name */ /** Strip dot suffix from a name */
private static String stripDotSuffix(String value) { private static String stripDotSuffix(final String value) {
int index = value.indexOf("."); final int index = value.indexOf(".");
if (index != -1) if (index != -1)
return value.substring(0, index); return value.substring(0, index);
return value; return value;
} }
/** Convert host to standard form */ /** Convert host to standard form */
private static String convertHost(String host) { private static String convertHost(final String host) {
return stripDotSuffix(host); return stripDotSuffix(host);
} }
/** Convert domain to standard form */ /** Convert domain to standard form */
private static String convertDomain(String domain) { private static String convertDomain(final String domain) {
return stripDotSuffix(domain); return stripDotSuffix(domain);
} }
private static int readULong(byte[] src, 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(byte[] src, 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);
} }
private static byte[] readSecurityBuffer(byte[] src, int index) throws NTLMEngineException { private static byte[] readSecurityBuffer(final byte[] src, final int index) throws NTLMEngineException {
int length = readUShort(src, index); final int length = readUShort(src, index);
int offset = readULong(src, index + 4); final 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]; final byte[] buffer = new byte[length];
System.arraycopy(src, offset, buffer, 0, length); System.arraycopy(src, offset, buffer, 0, length);
return buffer; return buffer;
} }
@ -228,7 +228,7 @@ final class NTLMEngineImpl implements NTLMEngine {
if (RND_GEN == null) { if (RND_GEN == null) {
throw new NTLMEngineException("Random generator not available"); throw new NTLMEngineException("Random generator not available");
} }
byte[] rval = new byte[8]; final byte[] rval = new byte[8];
synchronized (RND_GEN) { synchronized (RND_GEN) {
RND_GEN.nextBytes(rval); RND_GEN.nextBytes(rval);
} }
@ -240,7 +240,7 @@ final class NTLMEngineImpl implements NTLMEngine {
if (RND_GEN == null) { if (RND_GEN == null) {
throw new NTLMEngineException("Random generator not available"); throw new NTLMEngineException("Random generator not available");
} }
byte[] rval = new byte[16]; final byte[] rval = new byte[16];
synchronized (RND_GEN) { synchronized (RND_GEN) {
RND_GEN.nextBytes(rval); RND_GEN.nextBytes(rval);
} }
@ -280,10 +280,10 @@ final class NTLMEngineImpl implements NTLMEngine {
protected byte[] ntlm2SessionResponseUserSessionKey = null; protected byte[] ntlm2SessionResponseUserSessionKey = null;
protected byte[] lanManagerSessionKey = null; protected byte[] lanManagerSessionKey = null;
public CipherGen(String domain, String user, String password, public CipherGen(final String domain, final String user, final String password,
byte[] challenge, String target, byte[] targetInformation, final byte[] challenge, final String target, final byte[] targetInformation,
byte[] clientChallenge, byte[] clientChallenge2, final byte[] clientChallenge, final byte[] clientChallenge2,
byte[] secondaryKey, byte[] timestamp) { final byte[] secondaryKey, final byte[] timestamp) {
this.domain = domain; this.domain = domain;
this.target = target; this.target = target;
this.user = user; this.user = user;
@ -296,8 +296,8 @@ final class NTLMEngineImpl implements NTLMEngine {
this.timestamp = timestamp; this.timestamp = timestamp;
} }
public CipherGen(String domain, String user, String password, public CipherGen(final String domain, final String user, final String password,
byte[] challenge, String target, byte[] targetInformation) { final byte[] challenge, final String target, final byte[] targetInformation) {
this(domain, user, password, challenge, target, targetInformation, null, null, null, null); this(domain, user, password, challenge, target, targetInformation, null, null, null, null);
} }
@ -425,7 +425,7 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getLM2SessionResponse() public byte[] getLM2SessionResponse()
throws NTLMEngineException { throws NTLMEngineException {
if (lm2SessionResponse == null) { if (lm2SessionResponse == null) {
byte[] clientChallenge = getClientChallenge(); final byte[] clientChallenge = getClientChallenge();
lm2SessionResponse = new byte[24]; lm2SessionResponse = new byte[24];
System.arraycopy(clientChallenge, 0, lm2SessionResponse, 0, clientChallenge.length); System.arraycopy(clientChallenge, 0, lm2SessionResponse, 0, clientChallenge.length);
Arrays.fill(lm2SessionResponse, clientChallenge.length, lm2SessionResponse.length, (byte) 0x00); Arrays.fill(lm2SessionResponse, clientChallenge.length, lm2SessionResponse.length, (byte) 0x00);
@ -437,7 +437,7 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getLMUserSessionKey() public byte[] getLMUserSessionKey()
throws NTLMEngineException { throws NTLMEngineException {
if (lmUserSessionKey == null) { if (lmUserSessionKey == null) {
byte[] lmHash = getLMHash(); final byte[] lmHash = getLMHash();
lmUserSessionKey = new byte[16]; lmUserSessionKey = new byte[16];
System.arraycopy(lmHash, 0, lmUserSessionKey, 0, 8); System.arraycopy(lmHash, 0, lmUserSessionKey, 0, 8);
Arrays.fill(lmUserSessionKey, 8, 16, (byte) 0x00); Arrays.fill(lmUserSessionKey, 8, 16, (byte) 0x00);
@ -449,8 +449,8 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getNTLMUserSessionKey() public byte[] getNTLMUserSessionKey()
throws NTLMEngineException { throws NTLMEngineException {
if (ntlmUserSessionKey == null) { if (ntlmUserSessionKey == null) {
byte[] ntlmHash = getNTLMHash(); final byte[] ntlmHash = getNTLMHash();
MD4 md4 = new MD4(); final MD4 md4 = new MD4();
md4.update(ntlmHash); md4.update(ntlmHash);
ntlmUserSessionKey = md4.getOutput(); ntlmUserSessionKey = md4.getOutput();
} }
@ -461,8 +461,8 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getNTLMv2UserSessionKey() public byte[] getNTLMv2UserSessionKey()
throws NTLMEngineException { throws NTLMEngineException {
if (ntlmv2UserSessionKey == null) { if (ntlmv2UserSessionKey == null) {
byte[] ntlmv2hash = getNTLMv2Hash(); final byte[] ntlmv2hash = getNTLMv2Hash();
byte[] truncatedResponse = new byte[16]; final byte[] truncatedResponse = new byte[16];
System.arraycopy(getNTLMv2Response(), 0, truncatedResponse, 0, 16); System.arraycopy(getNTLMv2Response(), 0, truncatedResponse, 0, 16);
ntlmv2UserSessionKey = hmacMD5(truncatedResponse, ntlmv2hash); ntlmv2UserSessionKey = hmacMD5(truncatedResponse, ntlmv2hash);
} }
@ -473,9 +473,9 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getNTLM2SessionResponseUserSessionKey() public byte[] getNTLM2SessionResponseUserSessionKey()
throws NTLMEngineException { throws NTLMEngineException {
if (ntlm2SessionResponseUserSessionKey == null) { if (ntlm2SessionResponseUserSessionKey == null) {
byte[] ntlmUserSessionKey = getNTLMUserSessionKey(); final byte[] ntlmUserSessionKey = getNTLMUserSessionKey();
byte[] ntlm2SessionResponseNonce = getLM2SessionResponse(); final byte[] ntlm2SessionResponseNonce = getLM2SessionResponse();
byte[] sessionNonce = new byte[challenge.length + ntlm2SessionResponseNonce.length]; final byte[] sessionNonce = new byte[challenge.length + ntlm2SessionResponseNonce.length];
System.arraycopy(challenge, 0, sessionNonce, 0, challenge.length); System.arraycopy(challenge, 0, sessionNonce, 0, challenge.length);
System.arraycopy(ntlm2SessionResponseNonce, 0, sessionNonce, challenge.length, ntlm2SessionResponseNonce.length); System.arraycopy(ntlm2SessionResponseNonce, 0, sessionNonce, challenge.length, ntlm2SessionResponseNonce.length);
ntlm2SessionResponseUserSessionKey = hmacMD5(sessionNonce,ntlmUserSessionKey); ntlm2SessionResponseUserSessionKey = hmacMD5(sessionNonce,ntlmUserSessionKey);
@ -487,22 +487,22 @@ final class NTLMEngineImpl implements NTLMEngine {
public byte[] getLanManagerSessionKey() public byte[] getLanManagerSessionKey()
throws NTLMEngineException { throws NTLMEngineException {
if (lanManagerSessionKey == null) { if (lanManagerSessionKey == null) {
byte[] lmHash = getLMHash(); final byte[] lmHash = getLMHash();
byte[] lmResponse = getLMResponse(); final byte[] lmResponse = getLMResponse();
try { try {
byte[] keyBytes = new byte[14]; final byte[] keyBytes = new byte[14];
System.arraycopy(lmHash, 0, keyBytes, 0, 8); System.arraycopy(lmHash, 0, keyBytes, 0, 8);
Arrays.fill(keyBytes, 8, keyBytes.length, (byte)0xbd); Arrays.fill(keyBytes, 8, keyBytes.length, (byte)0xbd);
Key lowKey = createDESKey(keyBytes, 0); final Key lowKey = createDESKey(keyBytes, 0);
Key highKey = createDESKey(keyBytes, 7); final Key highKey = createDESKey(keyBytes, 7);
byte[] truncatedResponse = new byte[8]; final byte[] truncatedResponse = new byte[8];
System.arraycopy(lmResponse, 0, truncatedResponse, 0, truncatedResponse.length); System.arraycopy(lmResponse, 0, truncatedResponse, 0, truncatedResponse.length);
Cipher des = Cipher.getInstance("DES/ECB/NoPadding"); Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
des.init(Cipher.ENCRYPT_MODE, lowKey); des.init(Cipher.ENCRYPT_MODE, lowKey);
byte[] lowPart = des.doFinal(truncatedResponse); final byte[] lowPart = des.doFinal(truncatedResponse);
des = Cipher.getInstance("DES/ECB/NoPadding"); des = Cipher.getInstance("DES/ECB/NoPadding");
des.init(Cipher.ENCRYPT_MODE, highKey); des.init(Cipher.ENCRYPT_MODE, highKey);
byte[] highPart = des.doFinal(truncatedResponse); final byte[] highPart = des.doFinal(truncatedResponse);
lanManagerSessionKey = new byte[16]; lanManagerSessionKey = new byte[16];
System.arraycopy(lowPart, 0, lanManagerSessionKey, 0, lowPart.length); System.arraycopy(lowPart, 0, lanManagerSessionKey, 0, lowPart.length);
System.arraycopy(highPart, 0, lanManagerSessionKey, lowPart.length, highPart.length); System.arraycopy(highPart, 0, lanManagerSessionKey, lowPart.length, highPart.length);
@ -515,18 +515,18 @@ final class NTLMEngineImpl implements NTLMEngine {
} }
/** Calculates HMAC-MD5 */ /** Calculates HMAC-MD5 */
static byte[] hmacMD5(byte[] value, byte[] key) static byte[] hmacMD5(final byte[] value, final byte[] key)
throws NTLMEngineException { throws NTLMEngineException {
HMACMD5 hmacMD5 = new HMACMD5(key); final HMACMD5 hmacMD5 = new HMACMD5(key);
hmacMD5.update(value); hmacMD5.update(value);
return hmacMD5.getOutput(); return hmacMD5.getOutput();
} }
/** Calculates RC4 */ /** Calculates RC4 */
static byte[] RC4(byte[] value, byte[] key) static byte[] RC4(final byte[] value, final byte[] key)
throws NTLMEngineException { throws NTLMEngineException {
try { try {
Cipher rc4 = Cipher.getInstance("RC4"); final Cipher rc4 = Cipher.getInstance("RC4");
rc4.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "RC4")); rc4.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "RC4"));
return rc4.doFinal(value); return rc4.doFinal(value);
} catch (Exception e) { } catch (Exception e) {
@ -538,19 +538,12 @@ final class NTLMEngineImpl implements NTLMEngine {
* Calculates the NTLM2 Session Response for the given challenge, using the * Calculates the NTLM2 Session Response for the given challenge, using the
* specified password and client challenge. * specified password and client challenge.
* *
* @param password
* The user's password.
* @param challenge
* The Type 2 challenge from the server.
* @param clientChallenge
* The random 8-byte client challenge.
*
* @return The NTLM2 Session Response. This is placed in the NTLM response * @return The NTLM2 Session Response. This is placed in the NTLM response
* field of the Type 3 message; the LM response field contains the * field of the Type 3 message; the LM response field contains the
* client challenge, null-padded to 24 bytes. * client challenge, null-padded to 24 bytes.
*/ */
static byte[] ntlm2SessionResponse(byte[] ntlmHash, byte[] challenge, static byte[] ntlm2SessionResponse(final byte[] ntlmHash, final byte[] challenge,
byte[] clientChallenge) throws NTLMEngineException { final byte[] clientChallenge) throws NTLMEngineException {
try { try {
// Look up MD5 algorithm (was necessary on jdk 1.4.2) // Look up MD5 algorithm (was necessary on jdk 1.4.2)
// This used to be needed, but java 1.5.0_07 includes the MD5 // This used to be needed, but java 1.5.0_07 includes the MD5
@ -565,12 +558,12 @@ final class NTLMEngineImpl implements NTLMEngine {
// byte[] digest = (byte[])digestMethod.invoke(mdInstance,new // byte[] digest = (byte[])digestMethod.invoke(mdInstance,new
// Object[0]); // Object[0]);
MessageDigest md5 = MessageDigest.getInstance("MD5"); final MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(challenge); md5.update(challenge);
md5.update(clientChallenge); md5.update(clientChallenge);
byte[] digest = md5.digest(); final byte[] digest = md5.digest();
byte[] sessionHash = new byte[8]; final byte[] sessionHash = new byte[8];
System.arraycopy(digest, 0, sessionHash, 0, 8); System.arraycopy(digest, 0, sessionHash, 0, 8);
return lmResponse(ntlmHash, sessionHash); return lmResponse(ntlmHash, sessionHash);
} catch (Exception e) { } catch (Exception e) {
@ -589,21 +582,21 @@ final class NTLMEngineImpl implements NTLMEngine {
* @return The LM Hash of the given password, used in the calculation of the * @return The LM Hash of the given password, used in the calculation of the
* LM Response. * LM Response.
*/ */
private static byte[] lmHash(String password) throws NTLMEngineException { private static byte[] lmHash(final String password) throws NTLMEngineException {
try { try {
byte[] oemPassword = password.toUpperCase(Locale.US).getBytes("US-ASCII"); final byte[] oemPassword = password.toUpperCase(Locale.US).getBytes("US-ASCII");
int length = Math.min(oemPassword.length, 14); final int length = Math.min(oemPassword.length, 14);
byte[] keyBytes = new byte[14]; final byte[] keyBytes = new byte[14];
System.arraycopy(oemPassword, 0, keyBytes, 0, length); System.arraycopy(oemPassword, 0, keyBytes, 0, length);
Key lowKey = createDESKey(keyBytes, 0); final Key lowKey = createDESKey(keyBytes, 0);
Key highKey = createDESKey(keyBytes, 7); final Key highKey = createDESKey(keyBytes, 7);
byte[] magicConstant = "KGS!@#$%".getBytes("US-ASCII"); final byte[] magicConstant = "KGS!@#$%".getBytes("US-ASCII");
Cipher des = Cipher.getInstance("DES/ECB/NoPadding"); final Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
des.init(Cipher.ENCRYPT_MODE, lowKey); des.init(Cipher.ENCRYPT_MODE, lowKey);
byte[] lowHash = des.doFinal(magicConstant); final byte[] lowHash = des.doFinal(magicConstant);
des.init(Cipher.ENCRYPT_MODE, highKey); des.init(Cipher.ENCRYPT_MODE, highKey);
byte[] highHash = des.doFinal(magicConstant); final byte[] highHash = des.doFinal(magicConstant);
byte[] lmHash = new byte[16]; final byte[] lmHash = new byte[16];
System.arraycopy(lowHash, 0, lmHash, 0, 8); System.arraycopy(lowHash, 0, lmHash, 0, 8);
System.arraycopy(highHash, 0, lmHash, 8, 8); System.arraycopy(highHash, 0, lmHash, 8, 8);
return lmHash; return lmHash;
@ -621,10 +614,10 @@ final class NTLMEngineImpl implements NTLMEngine {
* @return The NTLM Hash of the given password, used in the calculation of * @return The NTLM Hash of the given password, used in the calculation of
* the NTLM Response and the NTLMv2 and LMv2 Hashes. * the NTLM Response and the NTLMv2 and LMv2 Hashes.
*/ */
private static byte[] ntlmHash(String password) throws NTLMEngineException { private static byte[] ntlmHash(final String password) throws NTLMEngineException {
try { try {
byte[] unicodePassword = password.getBytes("UnicodeLittleUnmarked"); final byte[] unicodePassword = password.getBytes("UnicodeLittleUnmarked");
MD4 md4 = new MD4(); final MD4 md4 = new MD4();
md4.update(unicodePassword); md4.update(unicodePassword);
return md4.getOutput(); return md4.getOutput();
} catch (java.io.UnsupportedEncodingException e) { } catch (java.io.UnsupportedEncodingException e) {
@ -635,20 +628,13 @@ final class NTLMEngineImpl implements NTLMEngine {
/** /**
* Creates the LMv2 Hash of the user's password. * Creates the LMv2 Hash of the user's password.
* *
* @param target
* The authentication target (i.e., domain).
* @param user
* The username.
* @param password
* The password.
*
* @return The LMv2 Hash, used in the calculation of the NTLMv2 and LMv2 * @return The LMv2 Hash, used in the calculation of the NTLMv2 and LMv2
* Responses. * Responses.
*/ */
private static byte[] lmv2Hash(String domain, String user, byte[] ntlmHash) private static byte[] lmv2Hash(final String domain, final String user, final byte[] ntlmHash)
throws NTLMEngineException { throws NTLMEngineException {
try { try {
HMACMD5 hmacMD5 = new HMACMD5(ntlmHash); final HMACMD5 hmacMD5 = new HMACMD5(ntlmHash);
// Upper case username, upper case domain! // Upper case username, upper case domain!
hmacMD5.update(user.toUpperCase(Locale.US).getBytes("UnicodeLittleUnmarked")); hmacMD5.update(user.toUpperCase(Locale.US).getBytes("UnicodeLittleUnmarked"));
hmacMD5.update(domain.toUpperCase(Locale.US).getBytes("UnicodeLittleUnmarked")); hmacMD5.update(domain.toUpperCase(Locale.US).getBytes("UnicodeLittleUnmarked"));
@ -661,20 +647,13 @@ final class NTLMEngineImpl implements NTLMEngine {
/** /**
* Creates the NTLMv2 Hash of the user's password. * Creates the NTLMv2 Hash of the user's password.
* *
* @param target
* The authentication target (i.e., domain).
* @param user
* The username.
* @param password
* The password.
*
* @return The NTLMv2 Hash, used in the calculation of the NTLMv2 and LMv2 * @return The NTLMv2 Hash, used in the calculation of the NTLMv2 and LMv2
* Responses. * Responses.
*/ */
private static byte[] ntlmv2Hash(String domain, String user, byte[] ntlmHash) private static byte[] ntlmv2Hash(final String domain, final String user, final byte[] ntlmHash)
throws NTLMEngineException { throws NTLMEngineException {
try { try {
HMACMD5 hmacMD5 = new HMACMD5(ntlmHash); final HMACMD5 hmacMD5 = new HMACMD5(ntlmHash);
// Upper case username, mixed case target!! // Upper case username, mixed case target!!
hmacMD5.update(user.toUpperCase(Locale.US).getBytes("UnicodeLittleUnmarked")); hmacMD5.update(user.toUpperCase(Locale.US).getBytes("UnicodeLittleUnmarked"));
hmacMD5.update(domain.getBytes("UnicodeLittleUnmarked")); hmacMD5.update(domain.getBytes("UnicodeLittleUnmarked"));
@ -694,21 +673,21 @@ final class NTLMEngineImpl implements NTLMEngine {
* *
* @return The response (either LM or NTLM, depending on the provided hash). * @return The response (either LM or NTLM, depending on the provided hash).
*/ */
private static byte[] lmResponse(byte[] hash, byte[] challenge) throws NTLMEngineException { private static byte[] lmResponse(final byte[] hash, final byte[] challenge) throws NTLMEngineException {
try { try {
byte[] keyBytes = new byte[21]; final byte[] keyBytes = new byte[21];
System.arraycopy(hash, 0, keyBytes, 0, 16); System.arraycopy(hash, 0, keyBytes, 0, 16);
Key lowKey = createDESKey(keyBytes, 0); final Key lowKey = createDESKey(keyBytes, 0);
Key middleKey = createDESKey(keyBytes, 7); final Key middleKey = createDESKey(keyBytes, 7);
Key highKey = createDESKey(keyBytes, 14); final Key highKey = createDESKey(keyBytes, 14);
Cipher des = Cipher.getInstance("DES/ECB/NoPadding"); final Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
des.init(Cipher.ENCRYPT_MODE, lowKey); des.init(Cipher.ENCRYPT_MODE, lowKey);
byte[] lowResponse = des.doFinal(challenge); final byte[] lowResponse = des.doFinal(challenge);
des.init(Cipher.ENCRYPT_MODE, middleKey); des.init(Cipher.ENCRYPT_MODE, middleKey);
byte[] middleResponse = des.doFinal(challenge); final byte[] middleResponse = des.doFinal(challenge);
des.init(Cipher.ENCRYPT_MODE, highKey); des.init(Cipher.ENCRYPT_MODE, highKey);
byte[] highResponse = des.doFinal(challenge); final byte[] highResponse = des.doFinal(challenge);
byte[] lmResponse = new byte[24]; final byte[] lmResponse = new byte[24];
System.arraycopy(lowResponse, 0, lmResponse, 0, 8); System.arraycopy(lowResponse, 0, lmResponse, 0, 8);
System.arraycopy(middleResponse, 0, lmResponse, 8, 8); System.arraycopy(middleResponse, 0, lmResponse, 8, 8);
System.arraycopy(highResponse, 0, lmResponse, 16, 8); System.arraycopy(highResponse, 0, lmResponse, 16, 8);
@ -732,13 +711,13 @@ final class NTLMEngineImpl implements NTLMEngine {
* @return The response (either NTLMv2 or LMv2, depending on the client * @return The response (either NTLMv2 or LMv2, depending on the client
* data). * data).
*/ */
private static byte[] lmv2Response(byte[] hash, byte[] challenge, byte[] clientData) private static byte[] lmv2Response(final byte[] hash, final byte[] challenge, final byte[] clientData)
throws NTLMEngineException { throws NTLMEngineException {
HMACMD5 hmacMD5 = new HMACMD5(hash); final HMACMD5 hmacMD5 = new HMACMD5(hash);
hmacMD5.update(challenge); hmacMD5.update(challenge);
hmacMD5.update(clientData); hmacMD5.update(clientData);
byte[] mac = hmacMD5.getOutput(); final byte[] mac = hmacMD5.getOutput();
byte[] lmv2Response = new byte[mac.length + clientData.length]; final byte[] lmv2Response = new byte[mac.length + clientData.length];
System.arraycopy(mac, 0, lmv2Response, 0, mac.length); System.arraycopy(mac, 0, lmv2Response, 0, mac.length);
System.arraycopy(clientData, 0, lmv2Response, mac.length, clientData.length); System.arraycopy(clientData, 0, lmv2Response, mac.length, clientData.length);
return lmv2Response; return lmv2Response;
@ -755,12 +734,12 @@ final class NTLMEngineImpl implements NTLMEngine {
* *
* @return The blob, used in the calculation of the NTLMv2 Response. * @return The blob, used in the calculation of the NTLMv2 Response.
*/ */
private static byte[] createBlob(byte[] clientChallenge, byte[] targetInformation, byte[] timestamp) { private static byte[] createBlob(final byte[] clientChallenge, final byte[] targetInformation, final byte[] timestamp) {
byte[] blobSignature = new byte[] { (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00 }; final byte[] blobSignature = new byte[] { (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00 };
byte[] reserved = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; final byte[] reserved = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
byte[] unknown1 = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; final byte[] unknown1 = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
byte[] unknown2 = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; final byte[] unknown2 = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
byte[] blob = new byte[blobSignature.length + reserved.length + timestamp.length + 8 final byte[] blob = new byte[blobSignature.length + reserved.length + timestamp.length + 8
+ unknown1.length + targetInformation.length + unknown2.length]; + unknown1.length + targetInformation.length + unknown2.length];
int offset = 0; int offset = 0;
System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length); System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length);
@ -792,10 +771,10 @@ final class NTLMEngineImpl implements NTLMEngine {
* @return A DES encryption key created from the key material starting at * @return A DES encryption key created from the key material starting at
* the specified offset in the given byte array. * the specified offset in the given byte array.
*/ */
private static Key createDESKey(byte[] bytes, int offset) { private static Key createDESKey(final byte[] bytes, final int offset) {
byte[] keyBytes = new byte[7]; final byte[] keyBytes = new byte[7];
System.arraycopy(bytes, offset, keyBytes, 0, 7); System.arraycopy(bytes, offset, keyBytes, 0, 7);
byte[] material = new byte[8]; final byte[] material = new byte[8];
material[0] = keyBytes[0]; material[0] = keyBytes[0];
material[1] = (byte) (keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1); material[1] = (byte) (keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1);
material[2] = (byte) (keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2); material[2] = (byte) (keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2);
@ -814,10 +793,10 @@ final class NTLMEngineImpl implements NTLMEngine {
* @param bytes * @param bytes
* The data whose parity bits are to be adjusted for odd parity. * The data whose parity bits are to be adjusted for odd parity.
*/ */
private static void oddParity(byte[] bytes) { private static void oddParity(final byte[] bytes) {
for (int i = 0; i < bytes.length; i++) { for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i]; final byte b = bytes[i];
boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^ (b >>> 4) ^ (b >>> 3) final boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^ (b >>> 4) ^ (b >>> 3)
^ (b >>> 2) ^ (b >>> 1)) & 0x01) == 0; ^ (b >>> 2) ^ (b >>> 1)) & 0x01) == 0;
if (needsParity) { if (needsParity) {
bytes[i] |= (byte) 0x01; bytes[i] |= (byte) 0x01;
@ -840,7 +819,7 @@ final class NTLMEngineImpl implements NTLMEngine {
} }
/** Constructor to use when message contents are known */ /** Constructor to use when message contents are known */
NTLMMessage(String messageBody, int expectedType) throws NTLMEngineException { NTLMMessage(final String messageBody, final int expectedType) throws NTLMEngineException {
messageContents = Base64.decodeBase64(EncodingUtils.getBytes(messageBody, messageContents = Base64.decodeBase64(EncodingUtils.getBytes(messageBody,
DEFAULT_CHARSET)); DEFAULT_CHARSET));
// Look for NTLM message // Look for NTLM message
@ -855,7 +834,7 @@ final class NTLMEngineImpl implements NTLMEngine {
} }
// 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); final 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));
@ -877,43 +856,43 @@ 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(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(byte[] buffer, 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);
} }
/** Read a ushort from a position within the message buffer */ /** Read a ushort from a position within the message buffer */
protected int readUShort(int position) throws NTLMEngineException { protected int readUShort(final int position) throws NTLMEngineException {
return NTLMEngineImpl.readUShort(messageContents, position); return NTLMEngineImpl.readUShort(messageContents, position);
} }
/** Read a ulong from a position within the message buffer */ /** Read a ulong from a position within the message buffer */
protected int readULong(int position) throws NTLMEngineException { protected int readULong(final int position) throws NTLMEngineException {
return NTLMEngineImpl.readULong(messageContents, position); return NTLMEngineImpl.readULong(messageContents, position);
} }
/** Read a security buffer from a position within the message buffer */ /** Read a security buffer from a position within the message buffer */
protected byte[] readSecurityBuffer(int position) throws NTLMEngineException { protected byte[] readSecurityBuffer(final int position) throws NTLMEngineException {
return NTLMEngineImpl.readSecurityBuffer(messageContents, position); return NTLMEngineImpl.readSecurityBuffer(messageContents, position);
} }
/** /**
* Prepares the object to create a response of the given length. * Prepares the object to create a response of the given length.
* *
* @param length * @param maxlength
* the maximum length of the response to prepare, not * the maximum length of the response to prepare, not
* including the type and the signature (which this method * including the type and the signature (which this method
* adds). * adds).
*/ */
protected void prepareResponse(int maxlength, int messageType) { protected void prepareResponse(final int maxlength, final int messageType) {
messageContents = new byte[maxlength]; messageContents = new byte[maxlength];
currentOutputPosition = 0; currentOutputPosition = 0;
addBytes(SIGNATURE); addBytes(SIGNATURE);
@ -926,7 +905,7 @@ final class NTLMEngineImpl implements NTLMEngine {
* @param b * @param b
* the byte to add. * the byte to add.
*/ */
protected void addByte(byte b) { protected void addByte(final byte b) {
messageContents[currentOutputPosition] = b; messageContents[currentOutputPosition] = b;
currentOutputPosition++; currentOutputPosition++;
} }
@ -937,21 +916,21 @@ final class NTLMEngineImpl implements NTLMEngine {
* @param bytes * @param bytes
* the bytes to add. * the bytes to add.
*/ */
protected void addBytes(byte[] bytes) { protected void addBytes(final byte[] bytes) {
for (byte b : bytes) { for (final byte b : bytes) {
messageContents[currentOutputPosition] = b; messageContents[currentOutputPosition] = b;
currentOutputPosition++; currentOutputPosition++;
} }
} }
/** Adds a USHORT to the response */ /** Adds a USHORT to the response */
protected void addUShort(int value) { protected void addUShort(final int value) {
addByte((byte) (value & 0xff)); addByte((byte) (value & 0xff));
addByte((byte) (value >> 8 & 0xff)); addByte((byte) (value >> 8 & 0xff));
} }
/** Adds a ULong to the response */ /** Adds a ULong to the response */
protected void addULong(int value) { protected void addULong(final int value) {
addByte((byte) (value & 0xff)); addByte((byte) (value & 0xff));
addByte((byte) (value >> 8 & 0xff)); addByte((byte) (value >> 8 & 0xff));
addByte((byte) (value >> 16 & 0xff)); addByte((byte) (value >> 16 & 0xff));
@ -965,12 +944,10 @@ final class NTLMEngineImpl implements NTLMEngine {
* @return The response as above. * @return The response as above.
*/ */
String getResponse() { String getResponse() {
byte[] resp; final byte[] resp;
if (messageContents.length > currentOutputPosition) { if (messageContents.length > currentOutputPosition) {
byte[] tmp = new byte[currentOutputPosition]; final byte[] tmp = new byte[currentOutputPosition];
for (int i = 0; i < currentOutputPosition; i++) { System.arraycopy(messageContents, 0, tmp, 0, currentOutputPosition);
tmp[i] = messageContents[i];
}
resp = tmp; resp = tmp;
} else { } else {
resp = messageContents; resp = messageContents;
@ -986,13 +963,13 @@ final class NTLMEngineImpl implements NTLMEngine {
protected byte[] domainBytes; protected byte[] domainBytes;
/** Constructor. Include the arguments the message will need */ /** Constructor. Include the arguments the message will need */
Type1Message(String domain, String host) throws NTLMEngineException { Type1Message(final String domain, final String host) throws NTLMEngineException {
super(); super();
try { try {
// Strip off domain name from the host! // Strip off domain name from the host!
String unqualifiedHost = convertHost(host); final String unqualifiedHost = convertHost(host);
// Use only the base domain name! // Use only the base domain name!
String unqualifiedDomain = convertDomain(domain); final String unqualifiedDomain = convertDomain(domain);
hostBytes = unqualifiedHost.getBytes("ASCII"); hostBytes = unqualifiedHost.getBytes("ASCII");
domainBytes = unqualifiedDomain.toUpperCase(Locale.US).getBytes("ASCII"); domainBytes = unqualifiedDomain.toUpperCase(Locale.US).getBytes("ASCII");
@ -1009,7 +986,7 @@ final class NTLMEngineImpl implements NTLMEngine {
String getResponse() { String getResponse() {
// Now, build the message. Calculate its length first, including // Now, build the message. Calculate its length first, including
// signature or type. // signature or type.
int finalLength = 32 + 8 /*+ hostBytes.length + domainBytes.length */; final int finalLength = 32 + 8 /*+ hostBytes.length + domainBytes.length */;
// Set up the response. This will initialize the signature, message // Set up the response. This will initialize the signature, message
// type, and flags. // type, and flags.
@ -1081,7 +1058,7 @@ final class NTLMEngineImpl implements NTLMEngine {
protected byte[] targetInfo; protected byte[] targetInfo;
protected int flags; protected int flags;
Type2Message(String message) throws NTLMEngineException { Type2Message(final String message) throws NTLMEngineException {
super(message, 2); super(message, 2);
// Type 2 message is laid out as follows: // Type 2 message is laid out as follows:
@ -1115,7 +1092,7 @@ final class NTLMEngineImpl implements NTLMEngine {
// in Type2 messages, so use the length of the packet to decide // in Type2 messages, so use the length of the packet to decide
// how to proceed instead // how to proceed instead
if (getMessageLength() >= 12 + 8) { if (getMessageLength() >= 12 + 8) {
byte[] bytes = readSecurityBuffer(12); final byte[] bytes = readSecurityBuffer(12);
if (bytes.length != 0) { if (bytes.length != 0) {
try { try {
target = new String(bytes, "UnicodeLittleUnmarked"); target = new String(bytes, "UnicodeLittleUnmarked");
@ -1129,7 +1106,7 @@ final class NTLMEngineImpl implements NTLMEngine {
targetInfo = null; targetInfo = null;
// TARGET_DESIRED flag cannot be relied on, so use packet length // TARGET_DESIRED flag cannot be relied on, so use packet length
if (getMessageLength() >= 40 + 8) { if (getMessageLength() >= 40 + 8) {
byte[] bytes = readSecurityBuffer(40); final byte[] bytes = readSecurityBuffer(40);
if (bytes.length != 0) { if (bytes.length != 0) {
targetInfo = bytes; targetInfo = bytes;
} }
@ -1173,19 +1150,19 @@ final class NTLMEngineImpl implements NTLMEngine {
/** Constructor. Pass the arguments we will need */ /** Constructor. Pass the arguments we will need */
Type3Message(String domain, String host, String user, String password, byte[] nonce, Type3Message(final String domain, final String host, final String user, final String password, final byte[] nonce,
int type2Flags, String target, byte[] targetInformation) final int type2Flags, final String target, final byte[] targetInformation)
throws NTLMEngineException { throws NTLMEngineException {
// Save the flags // Save the flags
this.type2Flags = type2Flags; this.type2Flags = type2Flags;
// Strip off domain name from the host! // Strip off domain name from the host!
String unqualifiedHost = convertHost(host); final String unqualifiedHost = convertHost(host);
// Use only the base domain name! // Use only the base domain name!
String unqualifiedDomain = convertDomain(domain); final String unqualifiedDomain = convertDomain(domain);
// Create a cipher generator class. Use domain BEFORE it gets modified! // Create a cipher generator class. Use domain BEFORE it gets modified!
CipherGen gen = new CipherGen(unqualifiedDomain, user, password, nonce, target, targetInformation); final CipherGen gen = new CipherGen(unqualifiedDomain, user, password, nonce, target, targetInformation);
// Use the new code to calculate the responses, including v2 if that // Use the new code to calculate the responses, including v2 if that
// seems warranted. // seems warranted.
@ -1253,26 +1230,26 @@ final class NTLMEngineImpl implements NTLMEngine {
/** Assemble the response */ /** Assemble the response */
@Override @Override
String getResponse() { String getResponse() {
int ntRespLen = ntResp.length; final int ntRespLen = ntResp.length;
int lmRespLen = lmResp.length; final int lmRespLen = lmResp.length;
int domainLen = domainBytes.length; final int domainLen = domainBytes.length;
int hostLen = hostBytes.length; final int hostLen = hostBytes.length;
int userLen = userBytes.length; final int userLen = userBytes.length;
int sessionKeyLen; final 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 final int lmRespOffset = 72; // allocate space for the version
int ntRespOffset = lmRespOffset + lmRespLen; final int ntRespOffset = lmRespOffset + lmRespLen;
int domainOffset = ntRespOffset + ntRespLen; final int domainOffset = ntRespOffset + ntRespLen;
int userOffset = domainOffset + domainLen; final int userOffset = domainOffset + domainLen;
int hostOffset = userOffset + userLen; final int hostOffset = userOffset + userLen;
int sessionKeyOffset = hostOffset + hostLen; final int sessionKeyOffset = hostOffset + hostLen;
int finalLength = sessionKeyOffset + sessionKeyLen; final int finalLength = sessionKeyOffset + sessionKeyLen;
// Start the response. Length includes signature and type // Start the response. Length includes signature and type
prepareResponse(finalLength, 3); prepareResponse(finalLength, 3);
@ -1367,26 +1344,26 @@ final class NTLMEngineImpl implements NTLMEngine {
} }
} }
static void writeULong(byte[] buffer, int value, int offset) { static void writeULong(final byte[] buffer, final int value, final int offset) {
buffer[offset] = (byte) (value & 0xff); buffer[offset] = (byte) (value & 0xff);
buffer[offset + 1] = (byte) (value >> 8 & 0xff); buffer[offset + 1] = (byte) (value >> 8 & 0xff);
buffer[offset + 2] = (byte) (value >> 16 & 0xff); buffer[offset + 2] = (byte) (value >> 16 & 0xff);
buffer[offset + 3] = (byte) (value >> 24 & 0xff); buffer[offset + 3] = (byte) (value >> 24 & 0xff);
} }
static int F(int x, int y, int z) { static int F(final int x, final int y, final int z) {
return ((x & y) | (~x & z)); return ((x & y) | (~x & z));
} }
static int G(int x, int y, int z) { static int G(final int x, final int y, final int z) {
return ((x & y) | (x & z) | (y & z)); return ((x & y) | (x & z) | (y & z));
} }
static int H(int x, int y, int z) { static int H(final int x, final int y, final int z) {
return (x ^ y ^ z); return (x ^ y ^ z);
} }
static int rotintlft(int val, int numbits) { static int rotintlft(final int val, final int numbits) {
return ((val << numbits) | (val >>> (32 - numbits))); return ((val << numbits) | (val >>> (32 - numbits)));
} }
@ -1408,7 +1385,7 @@ final class NTLMEngineImpl implements NTLMEngine {
MD4() { MD4() {
} }
void update(byte[] input) { void update(final byte[] input) {
// We always deal with 512 bits at a time. Correspondingly, there is // We always deal with 512 bits at a time. Correspondingly, there is
// a buffer 64 bytes long that we write data into until it gets // a buffer 64 bytes long that we write data into until it gets
// full. // full.
@ -1418,7 +1395,7 @@ final class NTLMEngineImpl implements NTLMEngine {
// We have enough data to do the next step. Do a partial copy // We have enough data to do the next step. Do a partial copy
// and a transform, updating inputIndex and curBufferPos // and a transform, updating inputIndex and curBufferPos
// accordingly // accordingly
int transferAmt = dataBuffer.length - curBufferPos; final int transferAmt = dataBuffer.length - curBufferPos;
System.arraycopy(input, inputIndex, dataBuffer, curBufferPos, transferAmt); System.arraycopy(input, inputIndex, dataBuffer, curBufferPos, transferAmt);
count += transferAmt; count += transferAmt;
curBufferPos = 0; curBufferPos = 0;
@ -1429,7 +1406,7 @@ final class NTLMEngineImpl implements NTLMEngine {
// If there's anything left, copy it into the buffer and leave it. // If there's anything left, copy it into the buffer and leave it.
// We know there's not enough left to process. // We know there's not enough left to process.
if (inputIndex < input.length) { if (inputIndex < input.length) {
int transferAmt = input.length - inputIndex; final int transferAmt = input.length - inputIndex;
System.arraycopy(input, inputIndex, dataBuffer, curBufferPos, transferAmt); System.arraycopy(input, inputIndex, dataBuffer, curBufferPos, transferAmt);
count += transferAmt; count += transferAmt;
curBufferPos += transferAmt; curBufferPos += transferAmt;
@ -1439,9 +1416,9 @@ final class NTLMEngineImpl implements NTLMEngine {
byte[] getOutput() { byte[] getOutput() {
// Feed pad/length data into engine. This must round out the input // Feed pad/length data into engine. This must round out the input
// to a multiple of 512 bits. // to a multiple of 512 bits.
int bufferIndex = (int) (count & 63L); final int bufferIndex = (int) (count & 63L);
int padLen = (bufferIndex < 56) ? (56 - bufferIndex) : (120 - bufferIndex); final int padLen = (bufferIndex < 56) ? (56 - bufferIndex) : (120 - bufferIndex);
byte[] postBytes = new byte[padLen + 8]; final byte[] postBytes = new byte[padLen + 8];
// Leading 0x80, specified amount of zero padding, then length in // Leading 0x80, specified amount of zero padding, then length in
// bits. // bits.
postBytes[0] = (byte) 0x80; postBytes[0] = (byte) 0x80;
@ -1454,7 +1431,7 @@ final class NTLMEngineImpl implements NTLMEngine {
update(postBytes); update(postBytes);
// Calculate final result // Calculate final result
byte[] result = new byte[16]; final byte[] result = new byte[16];
writeULong(result, A, 0); writeULong(result, A, 0);
writeULong(result, B, 4); writeULong(result, B, 4);
writeULong(result, C, 8); writeULong(result, C, 8);
@ -1464,7 +1441,7 @@ final class NTLMEngineImpl implements NTLMEngine {
protected void processBuffer() { protected void processBuffer() {
// Convert current buffer to 16 ulongs // Convert current buffer to 16 ulongs
int[] d = new int[16]; final int[] d = new int[16];
for (int i = 0; i < 16; i++) { for (int i = 0; i < 16; i++) {
d[i] = (dataBuffer[i * 4] & 0xff) + ((dataBuffer[i * 4 + 1] & 0xff) << 8) d[i] = (dataBuffer[i * 4] & 0xff) + ((dataBuffer[i * 4 + 1] & 0xff) << 8)
@ -1473,10 +1450,10 @@ final class NTLMEngineImpl implements NTLMEngine {
} }
// Do a round of processing // Do a round of processing
int AA = A; final int AA = A;
int BB = B; final int BB = B;
int CC = C; final int CC = C;
int DD = D; final int DD = D;
round1(d); round1(d);
round2(d); round2(d);
round3(d); round3(d);
@ -1487,7 +1464,7 @@ final class NTLMEngineImpl implements NTLMEngine {
} }
protected void round1(int[] d) { protected void round1(final int[] d) {
A = rotintlft((A + F(B, C, D) + d[0]), 3); A = rotintlft((A + F(B, C, D) + d[0]), 3);
D = rotintlft((D + F(A, B, C) + d[1]), 7); D = rotintlft((D + F(A, B, C) + d[1]), 7);
C = rotintlft((C + F(D, A, B) + d[2]), 11); C = rotintlft((C + F(D, A, B) + d[2]), 11);
@ -1509,7 +1486,7 @@ final class NTLMEngineImpl implements NTLMEngine {
B = rotintlft((B + F(C, D, A) + d[15]), 19); B = rotintlft((B + F(C, D, A) + d[15]), 19);
} }
protected void round2(int[] d) { protected void round2(final int[] d) {
A = rotintlft((A + G(B, C, D) + d[0] + 0x5a827999), 3); A = rotintlft((A + G(B, C, D) + d[0] + 0x5a827999), 3);
D = rotintlft((D + G(A, B, C) + d[4] + 0x5a827999), 5); D = rotintlft((D + G(A, B, C) + d[4] + 0x5a827999), 5);
C = rotintlft((C + G(D, A, B) + d[8] + 0x5a827999), 9); C = rotintlft((C + G(D, A, B) + d[8] + 0x5a827999), 9);
@ -1532,7 +1509,7 @@ final class NTLMEngineImpl implements NTLMEngine {
} }
protected void round3(int[] d) { protected void round3(final int[] d) {
A = rotintlft((A + H(B, C, D) + d[0] + 0x6ed9eba1), 3); A = rotintlft((A + H(B, C, D) + d[0] + 0x6ed9eba1), 3);
D = rotintlft((D + H(A, B, C) + d[8] + 0x6ed9eba1), 9); D = rotintlft((D + H(A, B, C) + d[8] + 0x6ed9eba1), 9);
C = rotintlft((C + H(D, A, B) + d[4] + 0x6ed9eba1), 11); C = rotintlft((C + H(D, A, B) + d[4] + 0x6ed9eba1), 11);
@ -1566,7 +1543,8 @@ final class NTLMEngineImpl implements NTLMEngine {
protected byte[] opad; protected byte[] opad;
protected MessageDigest md5; protected MessageDigest md5;
HMACMD5(byte[] key) throws NTLMEngineException { HMACMD5(final byte[] input) throws NTLMEngineException {
byte[] key = input;
try { try {
md5 = MessageDigest.getInstance("MD5"); md5 = MessageDigest.getInstance("MD5");
} catch (Exception ex) { } catch (Exception ex) {
@ -1607,18 +1585,18 @@ final class NTLMEngineImpl implements NTLMEngine {
/** Grab the current digest. This is the "answer". */ /** Grab the current digest. This is the "answer". */
byte[] getOutput() { byte[] getOutput() {
byte[] digest = md5.digest(); final byte[] digest = md5.digest();
md5.update(opad); md5.update(opad);
return md5.digest(digest); return md5.digest(digest);
} }
/** Update by adding a complete array */ /** Update by adding a complete array */
void update(byte[] input) { void update(final byte[] input) {
md5.update(input); md5.update(input);
} }
/** Update the algorithm */ /** Update the algorithm */
void update(byte[] input, int offset, int length) { void update(final byte[] input, final int offset, final int length) {
md5.update(input, offset, length); md5.update(input, offset, length);
} }
@ -1636,7 +1614,7 @@ final class NTLMEngineImpl implements NTLMEngine {
final String domain, final String domain,
final String workstation, final String workstation,
final String challenge) throws NTLMEngineException { final String challenge) throws NTLMEngineException {
Type2Message t2m = new Type2Message(challenge); final Type2Message t2m = new Type2Message(challenge);
return getType3Message( return getType3Message(
username, username,
password, password,

View File

@ -46,7 +46,6 @@ import org.apache.http.auth.AuthSchemeRegistry;
import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.MalformedChallengeException; import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.client.AuthenticationHandler; import org.apache.http.client.AuthenticationHandler;
import org.apache.http.client.AuthenticationStrategy;
import org.apache.http.client.params.AuthPolicy; import org.apache.http.client.params.AuthPolicy;
import org.apache.http.client.protocol.ClientContext; import org.apache.http.client.protocol.ClientContext;
import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HTTP;
@ -59,7 +58,7 @@ import org.apache.http.util.CharArrayBuffer;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.2) use {@link AuthenticationStrategy} * @deprecated (4.2) use {@link org.apache.http.client.AuthenticationStrategy}
*/ */
@Deprecated @Deprecated
@Immutable @Immutable
@ -84,7 +83,7 @@ public abstract class AbstractAuthenticationHandler implements AuthenticationHan
final Map<String, Header> map = new HashMap<String, Header>(headers.length); final Map<String, Header> map = new HashMap<String, Header>(headers.length);
for (final Header header : headers) { for (final Header header : headers) {
CharArrayBuffer buffer; final CharArrayBuffer buffer;
int pos; int pos;
if (header instanceof FormattedHeader) { if (header instanceof FormattedHeader) {
buffer = ((FormattedHeader) header).getBuffer(); buffer = ((FormattedHeader) header).getBuffer();

View File

@ -48,7 +48,6 @@ import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ConnectionBackoffStrategy; import org.apache.http.client.ConnectionBackoffStrategy;
import org.apache.http.client.CookieStore; import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider; import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.RedirectHandler; import org.apache.http.client.RedirectHandler;
import org.apache.http.client.RedirectStrategy; import org.apache.http.client.RedirectStrategy;
@ -94,10 +93,10 @@ import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.util.Args; import org.apache.http.util.Args;
/** /**
* Base class for {@link HttpClient} implementations. This class acts as * Base class for {@link org.apache.http.client.HttpClient} implementations.
* a facade to a number of special purpose handler or strategy * This class acts as a facade to a number of special purpose handler or
* implementations responsible for handling of a particular aspect of * strategy implementations responsible for handling of a particular aspect
* the HTTP protocol such as redirect or authentication handling or * of the HTTP protocol such as redirect or authentication handling or
* making decision about connection persistence and keep alive duration. * making decision about connection persistence and keep alive duration.
* This enables the users to selectively replace default implementation * This enables the users to selectively replace default implementation
* of those aspects with custom, application specific ones. This class * of those aspects with custom, application specific ones. This class
@ -702,7 +701,7 @@ public abstract class AbstractHttpClient extends CloseableHttpClient {
return mutableProcessor; return mutableProcessor;
} }
private synchronized final HttpProcessor getProtocolProcessor() { private synchronized HttpProcessor getProtocolProcessor() {
if (protocolProcessor == null) { if (protocolProcessor == null) {
// Get mutable HTTP processor // Get mutable HTTP processor
final BasicHttpProcessor proc = getHttpProcessor(); final BasicHttpProcessor proc = getHttpProcessor();
@ -833,7 +832,7 @@ public abstract class AbstractHttpClient extends CloseableHttpClient {
ClientPNames.DEFAULT_HOST); ClientPNames.DEFAULT_HOST);
final HttpRoute route = routePlanner.determineRoute(targetForRoute, request, execContext); final HttpRoute route = routePlanner.determineRoute(targetForRoute, request, execContext);
CloseableHttpResponse out; final CloseableHttpResponse out;
try { try {
out = CloseableHttpResponseProxy.newProxy( out = CloseableHttpResponseProxy.newProxy(
director.execute(target, request, execContext)); director.execute(target, request, execContext));

View File

@ -101,7 +101,7 @@ class AuthenticationStrategyAdaptor implements AuthenticationStrategy {
return options; return options;
} }
AuthScheme authScheme; final AuthScheme authScheme;
try { try {
authScheme = this.handler.selectScheme(challenges, response, context); authScheme = this.handler.selectScheme(challenges, response, context);
} catch (final AuthenticationException ex) { } catch (final AuthenticationException ex) {

View File

@ -102,7 +102,7 @@ abstract class AuthenticationStrategyImpl implements AuthenticationStrategy {
final Header[] headers = response.getHeaders(this.headerName); final Header[] headers = response.getHeaders(this.headerName);
final Map<String, Header> map = new HashMap<String, Header>(headers.length); final Map<String, Header> map = new HashMap<String, Header>(headers.length);
for (final Header header : headers) { for (final Header header : headers) {
CharArrayBuffer buffer; final CharArrayBuffer buffer;
int pos; int pos;
if (header instanceof FormattedHeader) { if (header instanceof FormattedHeader) {
buffer = ((FormattedHeader) header).getBuffer(); buffer = ((FormattedHeader) header).getBuffer();

View File

@ -29,7 +29,6 @@ package org.apache.http.impl.client;
import org.apache.http.annotation.NotThreadSafe; import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.params.AbstractHttpParams; import org.apache.http.params.AbstractHttpParams;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.util.Args; import org.apache.http.util.Args;
@ -67,7 +66,8 @@ import org.apache.http.util.Args;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link DefaultedHttpParams} * @deprecated (4.3) use configuration classes provided 'org.apache.http.config'
* and 'org.apache.http.client.config'
*/ */
@NotThreadSafe @NotThreadSafe
@Deprecated @Deprecated

View File

@ -213,7 +213,7 @@ public abstract class CloseableHttpClient implements HttpClient, Closeable {
final HttpResponse response = execute(target, request, context); final HttpResponse response = execute(target, request, context);
T result; final T result;
try { try {
result = responseHandler.handleResponse(response); result = responseHandler.handleResponse(response);
} catch (final Exception t) { } catch (final Exception t) {

View File

@ -27,7 +27,6 @@
package org.apache.http.impl.client; package org.apache.http.impl.client;
import org.apache.http.annotation.ThreadSafe; import org.apache.http.annotation.ThreadSafe;
import org.apache.http.client.HttpClient;
import org.apache.http.client.protocol.RequestAcceptEncoding; import org.apache.http.client.protocol.RequestAcceptEncoding;
import org.apache.http.client.protocol.ResponseContentEncoding; import org.apache.http.client.protocol.ResponseContentEncoding;
import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.ClientConnectionManager;
@ -40,11 +39,11 @@ import org.apache.http.protocol.BasicHttpProcessor;
* *
* <b>Deprecation note:</b> due to the way this class modifies a response body * <b>Deprecation note:</b> due to the way this class modifies a response body
* without changing the response headers to reflect the entity changes, it cannot * without changing the response headers to reflect the entity changes, it cannot
* be used as the &quot;backend&quot; for a caching {@link HttpClient} and still * be used as the &quot;backend&quot; for a caching {@link
* have uncompressed responses be cached. Users are encouraged to use the * org.apache.http.client.HttpClient} and still have uncompressed responses be cached.
* {@link DecompressingHttpClient} instead of this class, which can be wired in * Users are encouraged to use the {@link DecompressingHttpClient} instead
* either before or after caching, depending on whether you want to cache * of this class, which can be wired in either before or after caching, depending on
* responses in compressed or uncompressed form. * whether you want to cache responses in compressed or uncompressed form.
* *
* @since 4.1 * @since 4.1
* *

View File

@ -145,22 +145,20 @@ public class DecompressingHttpClient implements HttpClient {
} }
public HttpResponse execute(final HttpHost target, final HttpRequest request, public HttpResponse execute(final HttpHost target, final HttpRequest request,
HttpContext context) throws IOException, ClientProtocolException { final HttpContext context) throws IOException, ClientProtocolException {
try { try {
if (context == null) { final HttpContext localContext = context != null ? context : new BasicHttpContext();
context = new BasicHttpContext(); final HttpRequest wrapped;
}
HttpRequest wrapped;
if (request instanceof HttpEntityEnclosingRequest) { if (request instanceof HttpEntityEnclosingRequest) {
wrapped = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request); wrapped = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request);
} else { } else {
wrapped = new RequestWrapper(request); wrapped = new RequestWrapper(request);
} }
acceptEncodingInterceptor.process(wrapped, context); acceptEncodingInterceptor.process(wrapped, localContext);
final HttpResponse response = backend.execute(target, wrapped, context); final HttpResponse response = backend.execute(target, wrapped, localContext);
try { try {
contentEncodingInterceptor.process(response, context); contentEncodingInterceptor.process(response, localContext);
if (Boolean.TRUE.equals(context.getAttribute(ResponseContentEncoding.UNCOMPRESSED))) { if (Boolean.TRUE.equals(localContext.getAttribute(ResponseContentEncoding.UNCOMPRESSED))) {
response.removeHeaders("Content-Length"); response.removeHeaders("Content-Length");
response.removeHeaders("Content-Encoding"); response.removeHeaders("Content-Encoding");
response.removeHeaders("Content-MD5"); response.removeHeaders("Content-MD5");

View File

@ -29,7 +29,6 @@ package org.apache.http.impl.client;
import org.apache.http.HttpVersion; import org.apache.http.HttpVersion;
import org.apache.http.annotation.ThreadSafe; import org.apache.http.annotation.ThreadSafe;
import org.apache.http.client.HttpClient;
import org.apache.http.client.protocol.RequestAddCookies; import org.apache.http.client.protocol.RequestAddCookies;
import org.apache.http.client.protocol.RequestAuthCache; import org.apache.http.client.protocol.RequestAuthCache;
import org.apache.http.client.protocol.RequestClientConnControl; import org.apache.http.client.protocol.RequestClientConnControl;
@ -38,8 +37,6 @@ import org.apache.http.client.protocol.RequestProxyAuthentication;
import org.apache.http.client.protocol.RequestTargetAuthentication; import org.apache.http.client.protocol.RequestTargetAuthentication;
import org.apache.http.client.protocol.ResponseProcessCookies; import org.apache.http.client.protocol.ResponseProcessCookies;
import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams; import org.apache.http.params.HttpProtocolParams;
@ -53,7 +50,8 @@ import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.VersionInfo; import org.apache.http.util.VersionInfo;
/** /**
* Default implementation of {@link HttpClient} pre-configured for most common use scenarios. * Default implementation of {@link org.apache.http.client.HttpClient} pre-configured
* for most common use scenarios.
* <p> * <p>
* Please see the Javadoc for {@link #createHttpProcessor()} for the details of the interceptors * Please see the Javadoc for {@link #createHttpProcessor()} for the details of the interceptors
* that are set up by default. * that are set up by default.
@ -166,11 +164,16 @@ public class DefaultHttpClient extends AbstractHttpClient {
* Saves the default set of HttpParams in the provided parameter. * Saves the default set of HttpParams in the provided parameter.
* These are: * These are:
* <ul> * <ul>
* <li>{@link CoreProtocolPNames#PROTOCOL_VERSION}: 1.1</li> * <li>{@link org.apache.http.params.CoreProtocolPNames#PROTOCOL_VERSION}:
* <li>{@link CoreProtocolPNames#HTTP_CONTENT_CHARSET}: ISO-8859-1</li> * 1.1</li>
* <li>{@link CoreConnectionPNames#TCP_NODELAY}: true</li> * <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_CONTENT_CHARSET}:
* <li>{@link CoreConnectionPNames#SOCKET_BUFFER_SIZE}: 8192</li> * ISO-8859-1</li>
* <li>{@link CoreProtocolPNames#USER_AGENT}: Apache-HttpClient/<release> (java 1.5)</li> * <li>{@link org.apache.http.params.CoreConnectionPNames#TCP_NODELAY}:
* true</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}:
* 8192</li>
* <li>{@link org.apache.http.params.CoreProtocolPNames#USER_AGENT}:
* Apache-HttpClient/<release> (java 1.5)</li>
* </ul> * </ul>
*/ */
public static void setDefaultHttpParams(final HttpParams params) { public static void setDefaultHttpParams(final HttpParams params) {

View File

@ -37,13 +37,12 @@ import org.apache.http.annotation.Immutable;
import org.apache.http.auth.AUTH; import org.apache.http.auth.AUTH;
import org.apache.http.auth.MalformedChallengeException; import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.auth.params.AuthPNames; import org.apache.http.auth.params.AuthPNames;
import org.apache.http.client.AuthenticationHandler;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args; import org.apache.http.util.Args;
/** /**
* Default {@link AuthenticationHandler} implementation for proxy host * Default {@link org.apache.http.client.AuthenticationHandler} implementation
* authentication. * for proxy host authentication.
* *
* @since 4.0 * @since 4.0
* *

View File

@ -151,7 +151,7 @@ public class DefaultRedirectHandler implements RedirectHandler {
context.setAttribute(REDIRECT_LOCATIONS, redirectLocations); context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
} }
URI redirectURI; final URI redirectURI;
if (uri.getFragment() != null) { if (uri.getFragment() != null) {
try { try {
final HttpHost target = new HttpHost( final HttpHost target = new HttpHost(

View File

@ -86,7 +86,6 @@ import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestExecutor; import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.util.Args; import org.apache.http.util.Args;
import org.apache.http.util.Asserts;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
/** /**
@ -366,13 +365,15 @@ public class DefaultRequestDirector implements RequestDirector {
// non-javadoc, see interface ClientRequestDirector // non-javadoc, see interface ClientRequestDirector
public HttpResponse execute(HttpHost target, final HttpRequest request, public HttpResponse execute(final HttpHost targetHost, final HttpRequest request,
final HttpContext context) final HttpContext context)
throws HttpException, IOException { throws HttpException, IOException {
context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState); context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState);
context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);
HttpHost target = targetHost;
final HttpRequest orig = request; final HttpRequest orig = request;
final RequestWrapper origWrapper = wrapRequest(orig); final RequestWrapper origWrapper = wrapRequest(orig);
origWrapper.setParams(params); origWrapper.setParams(params);
@ -499,7 +500,7 @@ public class DefaultRequestDirector implements RequestDirector {
// Set the idle duration of this connection // Set the idle duration of this connection
final long duration = keepAliveStrategy.getKeepAliveDuration(response, context); final long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
if (this.log.isDebugEnabled()) { if (this.log.isDebugEnabled()) {
String s; final String s;
if (duration > 0) { if (duration > 0) {
s = "for " + duration + " " + TimeUnit.MILLISECONDS; s = "for " + duration + " " + TimeUnit.MILLISECONDS;
} else { } else {
@ -728,7 +729,7 @@ public class DefaultRequestDirector implements RequestDirector {
* Called by {@link #execute} * Called by {@link #execute}
* to determine the route for either the original or a followup request. * to determine the route for either the original or a followup request.
* *
* @param target the target host for the request. * @param targetHost the target host for the request.
* Implementations may accept <code>null</code> * Implementations may accept <code>null</code>
* if they can still determine a route, for example * if they can still determine a route, for example
* to a default target or by inspecting the request. * to a default target or by inspecting the request.
@ -740,17 +741,14 @@ public class DefaultRequestDirector implements RequestDirector {
* *
* @throws HttpException in case of a problem * @throws HttpException in case of a problem
*/ */
protected HttpRoute determineRoute(HttpHost target, protected HttpRoute determineRoute(final HttpHost targetHost,
final HttpRequest request, final HttpRequest request,
final HttpContext context) final HttpContext context)
throws HttpException { throws HttpException {
return this.routePlanner.determineRoute(
if (target == null) { targetHost != null ? targetHost : (HttpHost) request.getParams()
target = (HttpHost) request.getParams().getParameter( .getParameter(ClientPNames.DEFAULT_HOST),
ClientPNames.DEFAULT_HOST); request, context);
}
Asserts.notNull(target, "Target host");
return this.routePlanner.determineRoute(target, request, context);
} }

View File

@ -37,13 +37,12 @@ import org.apache.http.annotation.Immutable;
import org.apache.http.auth.AUTH; import org.apache.http.auth.AUTH;
import org.apache.http.auth.MalformedChallengeException; import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.auth.params.AuthPNames; import org.apache.http.auth.params.AuthPNames;
import org.apache.http.client.AuthenticationHandler;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args; import org.apache.http.util.Args;
/** /**
* Default {@link AuthenticationHandler} implementation for target host * Default {@link org.apache.http.client.AuthenticationHandler} implementation
* authentication. * for target host authentication.
* *
* @since 4.0 * @since 4.0
* *

View File

@ -32,7 +32,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
@ -68,7 +67,8 @@ public class FutureRequestExecutionService implements Closeable {
* and if you have less connections than threads, the threads will just end up * and if you have less connections than threads, the threads will just end up
* blocking on getting a connection from the pool. * blocking on getting a connection from the pool.
* @param executorService * @param executorService
* any executorService will do here. E.g. {@link Executors#newFixedThreadPool(int)} * any executorService will do here. E.g.
* {@link java.util.concurrent.Executors#newFixedThreadPool(int)}
*/ */
public FutureRequestExecutionService( public FutureRequestExecutionService(
final HttpClient httpclient, final HttpClient httpclient,

View File

@ -48,7 +48,6 @@ import org.apache.http.client.BackoffManager;
import org.apache.http.client.ConnectionBackoffStrategy; import org.apache.http.client.ConnectionBackoffStrategy;
import org.apache.http.client.CookieStore; import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider; import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.RedirectStrategy; import org.apache.http.client.RedirectStrategy;
import org.apache.http.client.ServiceUnavailableRetryStrategy; import org.apache.http.client.ServiceUnavailableRetryStrategy;
@ -111,7 +110,7 @@ import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.VersionInfo; import org.apache.http.util.VersionInfo;
/** /**
* {@link HttpClient} builder. * {@link CloseableHttpClient} builder.
* <p> * <p>
* The following system properties are taken into account by this class * The following system properties are taken into account by this class
* if the {@link #useSystemProperties()} method is called. * if the {@link #useSystemProperties()} method is called.
@ -207,6 +206,11 @@ public class HttpClientBuilder {
return this; return this;
} }
public final HttpClientBuilder setSslcontext(final SSLContext sslcontext) {
this.sslcontext = sslcontext;
return this;
}
public final HttpClientBuilder setConnectionManager( public final HttpClientBuilder setConnectionManager(
final HttpClientConnectionManager connManager) { final HttpClientConnectionManager connManager) {
this.connManager = connManager; this.connManager = connManager;
@ -412,6 +416,16 @@ public class HttpClientBuilder {
return this; return this;
} }
public final HttpClientBuilder disableCookieManagement() {
this.cookieManagementDisabled = true;
return this;
}
public final HttpClientBuilder disableAuthCaching() {
this.authCachingDisabled = true;
return this;
}
public final HttpClientBuilder useSystemProperties() { public final HttpClientBuilder useSystemProperties() {
systemProperties = true; systemProperties = true;
return this; return this;

View File

@ -28,15 +28,15 @@
package org.apache.http.impl.client; package org.apache.http.impl.client;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
import org.apache.http.client.RedirectStrategy;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
/** /**
* Lax {@link RedirectStrategy} implementation that automatically redirects all HEAD, GET and POST * Lax {@link org.apache.http.client.RedirectStrategy} implementation
* requests. This strategy relaxes restrictions on automatic redirection of POST methods imposed * that automatically redirects all HEAD, GET and POST requests.
* by the HTTP specification. * This strategy relaxes restrictions on automatic redirection of
* POST methods imposed by the HTTP specification.
* *
* @since 4.2 * @since 4.2
*/ */

View File

@ -32,11 +32,11 @@ import java.util.Collection;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
import org.apache.http.auth.AUTH; import org.apache.http.auth.AUTH;
import org.apache.http.client.AuthenticationStrategy;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
/** /**
* Default {@link AuthenticationStrategy} implementation for proxy host authentication. * Default {@link org.apache.http.client.AuthenticationStrategy} implementation
* for proxy host authentication.
* *
* @since 4.2 * @since 4.2
*/ */

View File

@ -30,10 +30,9 @@ package org.apache.http.impl.client;
import org.apache.http.annotation.NotThreadSafe; import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.URICollection; import org.apache.http.client.URICollection;
import java.net.URI;
/** /**
* This class represents a collection of {@link URI}s used as redirect locations. * This class represents a collection of {@link java.net.URI}s used
* as redirect locations.
* *
* @since 4.0 * @since 4.0
*/ */

View File

@ -33,12 +33,11 @@ import java.util.concurrent.ConcurrentHashMap;
import org.apache.http.HttpRequest; import org.apache.http.HttpRequest;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
import org.apache.http.client.HttpRequestRetryHandler;
/** /**
* A {@link HttpRequestRetryHandler} which assumes that all requested * {@link org.apache.http.client.HttpRequestRetryHandler} which assumes
* HTTP methods which should be idempotent according to RFC-2616 are * that all requested HTTP methods which should be idempotent according
* in fact idempotent and can be retried. * to RFC-2616 are in fact idempotent and can be retried.
* *
* According to RFC-2616 section 9.1.2 the idempotent HTTP methods are: * According to RFC-2616 section 9.1.2 the idempotent HTTP methods are:
* GET, HEAD, PUT, DELETE, OPTIONS, and TRACE * GET, HEAD, PUT, DELETE, OPTIONS, and TRACE

View File

@ -48,7 +48,7 @@ import org.apache.http.util.Args;
@ThreadSafe @ThreadSafe
public class SystemDefaultCredentialsProvider implements CredentialsProvider { public class SystemDefaultCredentialsProvider implements CredentialsProvider {
private static Map<String, String> SCHEME_MAP; private static final Map<String, String> SCHEME_MAP;
static { static {
SCHEME_MAP = new ConcurrentHashMap<String, String>(); SCHEME_MAP = new ConcurrentHashMap<String, String>();

View File

@ -32,11 +32,11 @@ import java.util.Collection;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.annotation.Immutable; import org.apache.http.annotation.Immutable;
import org.apache.http.auth.AUTH; import org.apache.http.auth.AUTH;
import org.apache.http.client.AuthenticationStrategy;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
/** /**
* Default {@link AuthenticationStrategy} implementation for proxy host authentication. * Default {@link org.apache.http.client.AuthenticationStrategy} implementation
* for proxy host authentication.
* *
* @since 4.2 * @since 4.2
*/ */

Some files were not shown because too many files have changed in this diff Show More