diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..8add43a4 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "dav4android"] + path = dav4android + url = git@gitlab.com:bitfireAT/dav4android.git diff --git a/app/build.gradle b/app/build.gradle index 4cfe8921..db2034fc 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -9,13 +9,14 @@ apply plugin: 'com.android.application' android { - compileSdkVersion 22 - buildToolsVersion '22.0.1' + compileSdkVersion 23 + buildToolsVersion '23.0.1' + useLibrary 'org.apache.http.legacy' defaultConfig { applicationId "at.bitfire.davdroid" minSdkVersion 14 - targetSdkVersion 22 + targetSdkVersion 23 } buildTypes { @@ -66,11 +67,13 @@ dependencies { // dnsjava for querying SRV/TXT records compile 'dnsjava:dnsjava:2.1.7' // HttpClient 4.3, Android flavour for WebDAV operations - //compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1' - compile project(':lib:httpclient-android') + compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1' + //compile project(':lib:httpclient-android') // SimpleXML for parsing and generating WebDAV messages compile('org.simpleframework:simple-xml:2.7.1') { exclude group: 'stax', module: 'stax-api' exclude group: 'xpp3', module: 'xpp3' } + + compile project(':dav4android') } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index f6ade0f7..078c8cb2 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -12,10 +12,6 @@ android:versionCode="72" android:versionName="0.8.4.1" android:installLocation="internalOnly"> - - diff --git a/app/src/main/java/at/bitfire/davdroid/Constants.java b/app/src/main/java/at/bitfire/davdroid/Constants.java index 495b28a2..4cfa5913 100644 --- a/app/src/main/java/at/bitfire/davdroid/Constants.java +++ b/app/src/main/java/at/bitfire/davdroid/Constants.java @@ -9,6 +9,9 @@ package at.bitfire.davdroid; import net.fortuna.ical4j.model.property.ProdId; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class Constants { public static final String APP_VERSION = "0.8.4.1", @@ -18,4 +21,6 @@ public class Constants { WEB_URL_VIEW_LOGS = "https://github.com/bitfireAT/davdroid/wiki/How-to-view-the-logs"; public static final ProdId ICAL_PRODID = new ProdId("-//bitfire web engineering//DAVdroid " + Constants.APP_VERSION + " (ical4j 2.0-beta1)//EN"); + + public static final Logger log = LoggerFactory.getLogger("DAVdroid"); } diff --git a/app/src/main/java/at/bitfire/davdroid/resource/DavResourceFinder.java b/app/src/main/java/at/bitfire/davdroid/resource/DavResourceFinder.java index 06eca62a..4690b348 100644 --- a/app/src/main/java/at/bitfire/davdroid/resource/DavResourceFinder.java +++ b/app/src/main/java/at/bitfire/davdroid/resource/DavResourceFinder.java @@ -8,10 +8,11 @@ package at.bitfire.davdroid.resource; import android.content.Context; +import android.text.TextUtils; import android.util.Log; -import org.apache.http.HttpException; -import org.apache.http.impl.client.CloseableHttpClient; +import com.squareup.okhttp.HttpUrl; + import org.xbill.DNS.Lookup; import org.xbill.DNS.Record; import org.xbill.DNS.SRVRecord; @@ -19,161 +20,137 @@ import org.xbill.DNS.TXTRecord; import org.xbill.DNS.TextParseException; import org.xbill.DNS.Type; -import java.io.Closeable; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.LinkedList; import java.util.List; -import at.bitfire.davdroid.R; -import at.bitfire.davdroid.webdav.DavException; -import at.bitfire.davdroid.webdav.DavHttpClient; -import at.bitfire.davdroid.webdav.DavIncapableException; -import at.bitfire.davdroid.webdav.HttpPropfind.Mode; -import at.bitfire.davdroid.webdav.NotAuthorizedException; -import at.bitfire.davdroid.webdav.WebDavResource; +import at.bitfire.dav4android.DavResource; +import at.bitfire.dav4android.HttpClient; +import at.bitfire.dav4android.exception.DavException; +import at.bitfire.dav4android.exception.HttpException; +import at.bitfire.dav4android.property.AddressbookDescription; +import at.bitfire.dav4android.property.AddressbookHomeSet; +import at.bitfire.dav4android.property.CalendarColor; +import at.bitfire.dav4android.property.CalendarDescription; +import at.bitfire.dav4android.property.CalendarHomeSet; +import at.bitfire.dav4android.property.CurrentUserPrincipal; +import at.bitfire.dav4android.property.DisplayName; +import at.bitfire.dav4android.property.ResourceType; +import at.bitfire.davdroid.Constants; +import at.bitfire.davdroid.DAVUtils; -public class DavResourceFinder implements Closeable { +public class DavResourceFinder { private final static String TAG = "davdroid.ResourceFinder"; final protected Context context; - final protected CloseableHttpClient httpClient; - + public DavResourceFinder(Context context) { this.context = context; - - // disable compression and enable network logging for debugging purposes - httpClient = DavHttpClient.create(); } - @Override - public void close() throws IOException { - httpClient.close(); - } - - - public void findResources(ServerInfo serverInfo) throws URISyntaxException, DavException, HttpException, IOException { - // CardDAV - Log.i(TAG, "*** Starting CardDAV resource detection"); - WebDavResource principal = getCurrentUserPrincipal(serverInfo, "carddav"); - URI uriAddressBookHomeSet = null; - try { - principal.propfind(Mode.HOME_SETS); - uriAddressBookHomeSet = principal.getProperties().getAddressbookHomeSet(); - } catch (Exception e) { - Log.i(TAG, "Couldn't find address-book home set", e); - } - if (uriAddressBookHomeSet != null) { - Log.i(TAG, "Found address-book home set: " + uriAddressBookHomeSet); - - WebDavResource homeSetAddressBooks = new WebDavResource(principal, uriAddressBookHomeSet); - if (checkHomesetCapabilities(homeSetAddressBooks, "addressbook")) { - serverInfo.setCardDAV(true); - homeSetAddressBooks.propfind(Mode.CARDDAV_COLLECTIONS); - - List possibleAddressBooks = new LinkedList<>(); - possibleAddressBooks.add(homeSetAddressBooks); - if (homeSetAddressBooks.getMembers() != null) - possibleAddressBooks.addAll(homeSetAddressBooks.getMembers()); - - List addressBooks = new LinkedList<>(); - for (WebDavResource resource : possibleAddressBooks) { - final WebDavResource.Properties properties = resource.getProperties(); - if (properties.isAddressBook()) { - Log.i(TAG, "Found address book: " + resource.getLocation().getPath()); - ServerInfo.ResourceInfo info = new ServerInfo.ResourceInfo( - ServerInfo.ResourceInfo.Type.ADDRESS_BOOK, - properties.isReadOnly(), - resource.getLocation().toString(), - properties.getDisplayName(), - properties.getDescription(), properties.getColor() - ); - - addressBooks.add(info); - } - } - serverInfo.setAddressBooks(addressBooks); - } else - Log.w(TAG, "Found address-book home set, but it doesn't advertise CardDAV support"); - } + public void findResources(final ServerInfo serverInfo) throws URISyntaxException, IOException, HttpException, DavException { + final HttpClient httpClient = new HttpClient(); + /*httpClient.setAuthenticator(new Authenticator() { + @Override + public Request authenticate(Proxy proxy, Response response) throws IOException { + String credential = Credentials.basic(serverInfo.getUserName(), serverInfo.getPassword()); + return response.request().newBuilder() + .header("Authorization", credential) + .build(); + } - // CalDAV - Log.i(TAG, "*** Starting CalDAV resource detection"); - principal = getCurrentUserPrincipal(serverInfo, "caldav"); - URI uriCalendarHomeSet = null; - try { - principal.propfind(Mode.HOME_SETS); - uriCalendarHomeSet = principal.getProperties().getCalendarHomeSet(); - } catch(Exception e) { - Log.i(TAG, "Couldn't find calendar home set", e); - } - if (uriCalendarHomeSet != null) { - Log.i(TAG, "Found calendar home set: " + uriCalendarHomeSet); - - WebDavResource homeSetCalendars = new WebDavResource(principal, uriCalendarHomeSet); - if (checkHomesetCapabilities(homeSetCalendars, "calendar-access")) { - serverInfo.setCalDAV(true); - homeSetCalendars.propfind(Mode.CALDAV_COLLECTIONS); - - List possibleCalendars = new LinkedList<>(); - possibleCalendars.add(homeSetCalendars); - if (homeSetCalendars.getMembers() != null) - possibleCalendars.addAll(homeSetCalendars.getMembers()); - - List - calendars = new LinkedList<>(), - todoLists = new LinkedList<>(); - for (WebDavResource resource : possibleCalendars) { - final WebDavResource.Properties properties = resource.getProperties(); - if (properties.isCalendar()) { - Log.i(TAG, "Found calendar: " + resource.getLocation().getPath()); - ServerInfo.ResourceInfo info = new ServerInfo.ResourceInfo( - ServerInfo.ResourceInfo.Type.CALENDAR, - properties.isReadOnly(), - resource.getLocation().toString(), - properties.getDisplayName(), - properties.getDescription(), properties.getColor() - ); - info.setTimezone(properties.getTimeZone()); - - boolean isCalendar = false, - isTodoList = false; - if (properties.getSupportedComponents() == null) { - // no info about supported components, assuming all components are supported - isCalendar = true; - isTodoList = true; - } else { - // CALDAV:supported-calendar-component-set available - for (String supportedComponent : properties.getSupportedComponents()) - if ("VEVENT".equalsIgnoreCase(supportedComponent)) - isCalendar = true; - else if ("VTODO".equalsIgnoreCase(supportedComponent)) - isTodoList = true; - - if (!isCalendar && !isTodoList) { - Log.i(TAG, "Ignoring this calendar because it supports neither VEVENT nor VTODO"); - continue; - } - } + @Override + public Request authenticateProxy(Proxy proxy, Response response) throws IOException { + return null; + } + });*/ - // use a copy constructor to allow different "enabled" status for calendars and todo lists - if (isCalendar) - calendars.add(new ServerInfo.ResourceInfo(info)); - if (isTodoList) - todoLists.add(new ServerInfo.ResourceInfo(info)); - } - } + // CardDAV + Constants.log.info("*** CardDAV resource detection ***"); + HttpUrl principalUrl = getCurrentUserPrincipal(httpClient, serverInfo, "carddav"); - serverInfo.setCalendars(calendars); - serverInfo.setTodoLists(todoLists); - } else - Log.w(TAG, "Found calendar home set, but it doesn't advertise CalDAV support"); - } + DavResource principal = new DavResource(httpClient, principalUrl); + principal.propfind(0, AddressbookHomeSet.NAME); + AddressbookHomeSet addrHomeSet = (AddressbookHomeSet)principal.properties.get(AddressbookHomeSet.NAME); + if (addrHomeSet != null && !addrHomeSet.hrefs.isEmpty()) { + Constants.log.info("Found addressbook home set(s): " + addrHomeSet); + serverInfo.setCardDAV(true); + + // enumerate address books + List addressBooks = new LinkedList<>(); + for (String href : addrHomeSet.hrefs) { + DavResource homeSet = new DavResource(httpClient, principalUrl.resolve(href)); + homeSet.propfind(1, ResourceType.NAME, DisplayName.NAME, AddressbookDescription.NAME); + for (DavResource member : homeSet.members) { + ResourceType type = (ResourceType)member.properties.get(ResourceType.NAME); + if (type != null && type.types.contains(ResourceType.ADDRESSBOOK)) { + Constants.log.info("Found address book: " + member.location); + + DisplayName displayName = (DisplayName)member.properties.get(DisplayName.NAME); + AddressbookDescription description = (AddressbookDescription)member.properties.get(AddressbookDescription.NAME); + + // TODO read-only + + addressBooks.add(new ServerInfo.ResourceInfo( + ServerInfo.ResourceInfo.Type.ADDRESS_BOOK, + false, + member.location.toString(), + displayName != null ? displayName.displayName : null, + description != null ? description.description : null, + null + )); + } + } + } + serverInfo.setAddressBooks(addressBooks); + } - if (!serverInfo.isCalDAV() && !serverInfo.isCardDAV()) - throw new DavIncapableException(context.getString(R.string.setup_neither_caldav_nor_carddav)); + // CalDAV + Constants.log.info("*** CalDAV resource detection ***"); + principalUrl = getCurrentUserPrincipal(httpClient, serverInfo, "caldav"); + + principal = new DavResource(httpClient, principalUrl); + principal.propfind(0, CalendarHomeSet.NAME); + CalendarHomeSet calHomeSet = (CalendarHomeSet)principal.properties.get(CalendarHomeSet.NAME); + if (calHomeSet != null && !calHomeSet.hrefs.isEmpty()) { + Constants.log.info("Found calendar home set(s): " + calHomeSet); + serverInfo.setCalDAV(true); + + // enumerate address books + List calendars = new LinkedList<>(); + for (String href : calHomeSet.hrefs) { + DavResource homeSet = new DavResource(httpClient, principalUrl.resolve(href)); + homeSet.propfind(1, ResourceType.NAME, DisplayName.NAME, CalendarDescription.NAME, CalendarColor.NAME); + for (DavResource member : homeSet.members) { + ResourceType type = (ResourceType)member.properties.get(ResourceType.NAME); + if (type != null && type.types.contains(ResourceType.CALENDAR)) { + Constants.log.info("Found calendar: " + member.location); + + DisplayName displayName = (DisplayName)member.properties.get(DisplayName.NAME); + CalendarDescription description = (CalendarDescription)member.properties.get(CalendarDescription.NAME); + CalendarColor color = (CalendarColor)member.properties.get(CalendarColor.NAME); + + // TODO read-only, time-zone, supported components + + calendars.add(new ServerInfo.ResourceInfo( + ServerInfo.ResourceInfo.Type.ADDRESS_BOOK, + false, + member.location.toString(), + displayName != null ? displayName.displayName : null, + description != null ? description.description : null, + color != null ? DAVUtils.CalDAVtoARGBColor(color.color) : null + )); + } + } + } + serverInfo.setCalendars(calendars); + } + + /*if (!serverInfo.isCalDAV() && !serverInfo.isCardDAV()) + throw new DavIncapableException(context.getString(R.string.setup_neither_caldav_nor_carddav));*/ } @@ -184,7 +161,7 @@ public class DavResourceFinder implements Closeable { * @return Initial service URL (HTTP/HTTPS), without user credentials * @throws URISyntaxException when the user-given URI is invalid */ - public URI getInitialContextURL(ServerInfo serverInfo, String serviceName) throws URISyntaxException { + public HttpUrl getInitialContextURL(ServerInfo serverInfo, String serviceName) throws URISyntaxException { String scheme, domain; int port = -1; @@ -215,7 +192,7 @@ public class DavResourceFinder implements Closeable { // try to determine FQDN and port number using SRV records try { String name = "_" + serviceName + "s._tcp." + domain; - Log.d(TAG, "Looking up SRV records for " + name); + Constants.log.debug("Looking up SRV records for " + name); Record[] records = new Lookup(name, Type.SRV).run(); if (records != null && records.length >= 1) { SRVRecord srv = selectSRVRecord(records); @@ -224,9 +201,6 @@ public class DavResourceFinder implements Closeable { domain = srv.getTarget().toString(true); port = srv.getPort(); Log.d(TAG, "Found " + serviceName + "s service for " + domain + " -> " + domain + ":" + port); - - if (port == 443) // no reason to explicitly give the default port - port = -1; // SRV record found, look for TXT record too (for initial context path) records = new Lookup(name, Type.TXT).run(); @@ -236,7 +210,7 @@ public class DavResourceFinder implements Closeable { String segment = (String)o; if (segment.startsWith("path=")) { path = segment.substring(5); - Log.d(TAG, "Found initial context path for " + serviceName + " at " + domain + " -> " + path); + Constants.log.debug("Found initial context path for " + serviceName + " at " + domain + " -> " + path); break; } } @@ -246,7 +220,12 @@ public class DavResourceFinder implements Closeable { throw new URISyntaxException(domain, "Invalid domain name"); } - return new URI(scheme, null, domain, port, path, null, null); + HttpUrl.Builder builder = new HttpUrl.Builder().scheme(scheme).host(domain); + if (port != -1) + builder.port(port); + if (TextUtils.isEmpty(path)) + path = "/"; + return builder.encodedPath(path).build(); } @@ -256,79 +235,59 @@ public class DavResourceFinder implements Closeable { * is tried. * @param serverInfo Location that will be queried * @param serviceName Well-known service name ("carddav", "caldav") - * @return WebDavResource of current-user-principal for the given service, or null if it can't be found + * @return WebDavResource of current-user-principal for the given service, or initial context URL if it can't be found * * TODO: If a TXT record is given, always use it instead of trying .well-known first */ - WebDavResource getCurrentUserPrincipal(ServerInfo serverInfo, String serviceName) throws URISyntaxException, IOException, NotAuthorizedException { - URI initialURL = getInitialContextURL(serverInfo, serviceName); - if (initialURL != null) { - Log.i(TAG, "Looking up principal URL for service " + serviceName + "; initial context: " + initialURL); - - // determine base URL (host name and initial context path) - WebDavResource base = new WebDavResource(httpClient, - initialURL, - serverInfo.getUserName(), serverInfo.getPassword(), serverInfo.isAuthPreemptive()); - - // look for well-known service (RFC 5785) - try { - WebDavResource wellKnown = new WebDavResource(base, new URI("/.well-known/" + serviceName)); - wellKnown.propfind(Mode.CURRENT_USER_PRINCIPAL); - if (wellKnown.getProperties().getCurrentUserPrincipal() != null) { - URI principal = wellKnown.getProperties().getCurrentUserPrincipal(); - Log.i(TAG, "Principal URL found from Well-Known URI: " + principal); - return new WebDavResource(wellKnown, principal); - } - } catch (NotAuthorizedException e) { - Log.w(TAG, "Not authorized for well-known " + serviceName + " service detection", e); - throw e; - } catch (URISyntaxException e) { - Log.e(TAG, "Well-known" + serviceName + " service detection failed because of invalid URIs", e); - } catch (HttpException e) { - Log.d(TAG, "Well-known " + serviceName + " service detection failed with HTTP error", e); - } catch (DavException e) { - Log.w(TAG, "Well-known " + serviceName + " service detection failed with unexpected DAV response", e); - } catch (IOException e) { - Log.e(TAG, "Well-known " + serviceName + " service detection failed with I/O error", e); - } + HttpUrl getCurrentUserPrincipal(HttpClient httpClient, ServerInfo serverInfo, String serviceName) throws URISyntaxException { + HttpUrl initialURL = getInitialContextURL(serverInfo, serviceName); - // fall back to user-given initial context path - Log.d(TAG, "Well-known service detection failed, trying initial context path " + initialURL); - try { - base.propfind(Mode.CURRENT_USER_PRINCIPAL); - if (base.getProperties().getCurrentUserPrincipal() != null) { - URI principal = base.getProperties().getCurrentUserPrincipal(); - Log.i(TAG, "Principal URL found from initial context path: " + principal); - return new WebDavResource(base, principal); - } - } catch (NotAuthorizedException e) { - Log.e(TAG, "Not authorized for querying principal", e); - throw e; - } catch (HttpException e) { - Log.e(TAG, "HTTP error when querying principal", e); - } catch (DavException e) { - Log.e(TAG, "DAV error when querying principal", e); - } + if (initialURL != null) { + Constants.log.info("Looking up principal URL for service " + serviceName + "; initial context: " + initialURL); - Log.i(TAG, "Couldn't find current-user-principal for service " + serviceName + ", assuming initial context path is principal path"); - return base; - } - return null; - } - - public static boolean checkHomesetCapabilities(WebDavResource resource, String davCapability) throws URISyntaxException, IOException { - // check for necessary capabilities - try { - resource.options(); - if (resource.supportsDAV(davCapability) && - resource.supportsMethod("PROPFIND")) // check only for methods that MUST be available for home sets - return true; - } catch(HttpException e) { - // for instance, 405 Method not allowed - } - return false; + // look for well-known service (RFC 5785) + try { + DavResource wellKnown = new DavResource(httpClient, initialURL.resolve("/.well-known/" + serviceName)); + wellKnown.propfind(0, CurrentUserPrincipal.NAME); + + CurrentUserPrincipal principal = (CurrentUserPrincipal)wellKnown.properties.get(CurrentUserPrincipal.NAME); + if (principal != null) { + HttpUrl url = wellKnown.location.resolve(principal.href); + Constants.log.info("Found principal URL from well-known URL: " + url); + return url; + } + } catch (IOException e) { + Constants.log.warn("Well-known " + serviceName + " service detection failed with I/O error", e); + } catch (HttpException e) { + Constants.log.warn("Well-known " + serviceName + " service detection failed with HTTP error", e); + } catch (DavException e) { + Constants.log.warn("Well-known " + serviceName + " service detection failed with DAV error", e); + } + } + + // fall back to user-given initial context path + Log.d(TAG, "Well-known service detection failed, trying initial context path " + initialURL); + try { + DavResource base = new DavResource(httpClient, initialURL); + base.propfind(0, CurrentUserPrincipal.NAME); + CurrentUserPrincipal principal = (CurrentUserPrincipal)base.properties.get(CurrentUserPrincipal.NAME); + if (principal != null) { + HttpUrl url = base.location.resolve(principal.href); + Constants.log.info("Found principal URL from initial context URL: " + url); + return url; + } + } catch (IOException e) { + Constants.log.warn("Well-known " + serviceName + " service detection failed with I/O error", e); + } catch (HttpException e) { + Log.e(TAG, "HTTP error when querying principal", e); + } catch (DavException e) { + Log.e(TAG, "DAV error when querying principal", e); + } + + Log.i(TAG, "Couldn't find current-user-principal for service " + serviceName + ". Assuming principal path is initial context path!"); + return initialURL; } - + SRVRecord selectSRVRecord(Record[] records) { if (records.length > 1) diff --git a/app/src/main/java/at/bitfire/davdroid/ui/setup/QueryServerDialogFragment.java b/app/src/main/java/at/bitfire/davdroid/ui/setup/QueryServerDialogFragment.java index c84c3639..eac458cb 100644 --- a/app/src/main/java/at/bitfire/davdroid/ui/setup/QueryServerDialogFragment.java +++ b/app/src/main/java/at/bitfire/davdroid/ui/setup/QueryServerDialogFragment.java @@ -21,19 +21,18 @@ import android.view.ViewGroup; import android.widget.Toast; import org.apache.commons.lang3.exception.ExceptionUtils; -import org.apache.http.HttpException; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.security.cert.CertPathValidatorException; +import at.bitfire.dav4android.exception.DavException; +import at.bitfire.dav4android.exception.HttpException; import at.bitfire.davdroid.R; import at.bitfire.davdroid.resource.DavResourceFinder; import at.bitfire.davdroid.resource.LocalTaskList; import at.bitfire.davdroid.resource.ServerInfo; -import at.bitfire.davdroid.webdav.DavException; -import lombok.Cleanup; public class QueryServerDialogFragment extends DialogFragment implements LoaderCallbacks { private static final String TAG = "davdroid.QueryServer"; @@ -113,7 +112,7 @@ public class QueryServerDialogFragment extends DialogFragment implements LoaderC ); try { - @Cleanup DavResourceFinder finder = new DavResourceFinder(context); + DavResourceFinder finder = new DavResourceFinder(context); finder.findResources(serverInfo); } catch (URISyntaxException e) { serverInfo.setErrorMessage(getContext().getString(R.string.exception_uri_syntax, e.getMessage())); @@ -127,9 +126,9 @@ public class QueryServerDialogFragment extends DialogFragment implements LoaderC Log.e(TAG, "HTTP error while querying server info", e); serverInfo.setErrorMessage(getContext().getString(R.string.exception_http, e.getLocalizedMessage())); } catch (DavException e) { - Log.e(TAG, "DAV error while querying server info", e); - serverInfo.setErrorMessage(getContext().getString(R.string.exception_incapable_resource, e.getLocalizedMessage())); - } + Log.e(TAG, "DAV error while querying server info", e); + serverInfo.setErrorMessage(getContext().getString(R.string.exception_incapable_resource, e.getLocalizedMessage())); + } return serverInfo; } diff --git a/build.gradle b/build.gradle index eaab37ef..43cd7530 100644 --- a/build.gradle +++ b/build.gradle @@ -12,13 +12,15 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:1.0.1' + classpath 'com.android.tools.build:gradle:1.3.1' } } allprojects { repositories { jcenter() - mavenCentral() + maven { + url 'http://oss.sonatype.org/content/repositories/snapshots' + } } } diff --git a/dav4android b/dav4android new file mode 160000 index 00000000..c8dffb7f --- /dev/null +++ b/dav4android @@ -0,0 +1 @@ +Subproject commit c8dffb7fa114a3ca46917ac18088cda981f0afd5 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 8c0fb64a..c97a8bdb 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index ec6ce241..5dda8f83 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,14 +1,6 @@ -# -# Copyright (c) 2013 – 2015 Ricki Hirner (bitfire web engineering). -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the GNU Public License v3.0 -# which accompanies this distribution, and is available at -# http://www.gnu.org/licenses/gpl.html -# - -#Wed Apr 10 15:27:10 PDT 2013 +#Fri Oct 09 23:40:23 CEST 2015 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-bin.zip diff --git a/lib/httpclient-android/BUILDING.txt b/lib/httpclient-android/BUILDING.txt deleted file mode 100644 index 27cddb18..00000000 --- a/lib/httpclient-android/BUILDING.txt +++ /dev/null @@ -1,39 +0,0 @@ -Building HttpComponents Client for Android -============================ - -(1) Requisites --------------- -Android SDK rev. 17 (4.2.2 or Jelly Bean MR1) or newer is required in order -to compile HttpClient for Android. Android SDK can be downloaded either separately -or bundled with Android Studio. - -HttpClient for Android utilizes Gradle as a building and packaging tool. -Version 2.2.1 or later is recommended. - -Gradle installation and configuration instructions can be found here: - -http://www.gradle.org/ - -(2) Building artifacts - -Set environmental variable ANDROID_HOME to the location of the Android SDK. - -Execute the following command in order to build binary, source and javadoc artifacts. - -gradle -q assemble - -Please note that when building a release version (project version does not have -'-SNAPSHOT' qualifier) one must also provide signing key details in gradle.properties -file in order to be able to sign the artifacts and successfully build the release. - ---- -signing.keyId=AEAEAEAE -signing.secretKeyRingFile=~/.gnupg/secring.gpg ---- - -The artifacts can be found in the 'build/libs' folder - -build/libs/httpclient-android-.jar -build/libs/httpclient-android--javadoc.jar -build/libs/httpclient-android--sources.jar - diff --git a/lib/httpclient-android/LICENSE.txt b/lib/httpclient-android/LICENSE.txt deleted file mode 100644 index 72819a9f..00000000 --- a/lib/httpclient-android/LICENSE.txt +++ /dev/null @@ -1,241 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - -========================================================================= - -This project contains annotations in the package org.apache.http.annotation -which are derived from JCIP-ANNOTATIONS -Copyright (c) 2005 Brian Goetz and Tim Peierls. -See http://www.jcip.net and the Creative Commons Attribution License -(http://creativecommons.org/licenses/by/2.5) -Full text: http://creativecommons.org/licenses/by/2.5/legalcode - -License - -THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. - -BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. - -1. Definitions - - "Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License. - "Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License. - "Licensor" means the individual or entity that offers the Work under the terms of this License. - "Original Author" means the individual or entity who created the Work. - "Work" means the copyrightable work of authorship offered under the terms of this License. - "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. - -2. Fair Use Rights. Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws. - -3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: - - to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works; - to create and reproduce Derivative Works; - to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works; - to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works. - - For the avoidance of doubt, where the work is a musical composition: - Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work. - Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights agency or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions). - Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions). - -The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved. - -4. Restrictions.The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: - - You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(b), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(b), as requested. - If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit. - -5. Representations, Warranties and Disclaimer - -UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. - -6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -7. Termination - - This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. - Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. - -8. Miscellaneous - - Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. - Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License. - If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. - No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. - This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. diff --git a/lib/httpclient-android/NOTICE.txt b/lib/httpclient-android/NOTICE.txt deleted file mode 100644 index 46fcefc3..00000000 --- a/lib/httpclient-android/NOTICE.txt +++ /dev/null @@ -1,8 +0,0 @@ -Apache HttpComponents HttpClient for Android -Copyright 2005-2014 The Apache Software Foundation - -This product includes software developed at -The Apache Software Foundation (http://www.apache.org/). - -This project contains annotations derived from JCIP-ANNOTATIONS -Copyright (c) 2005 Brian Goetz and Tim Peierls. See http://www.jcip.net diff --git a/lib/httpclient-android/README.txt b/lib/httpclient-android/README.txt deleted file mode 100644 index ae61f109..00000000 --- a/lib/httpclient-android/README.txt +++ /dev/null @@ -1,46 +0,0 @@ -This project represents an effort to provide an implementation of Apache HttpClient, which can be -deployed on Google Android in parallel to the outdated version shipped with platform while -remaining partially API compatible with Apache HttpClient 4.3. - -Background ----------- - -Google Android 1.0 was released with a pre-BETA snapshot of Apache HttpClient 4.0. To coincide with -the first Android release Apache HttpClient 4.0 APIs had to be frozen prematurely, while many of -interfaces and internal structures were still not fully worked out. As Apache HttpClient 4.0 was -maturing the project was expecting Google to incorporate the latest code improvements into their -code tree. Unfortunately it did not happen. Version of Apache HttpClient shipped with Android has -effectively became a fork. Eventually Google decided to discontinue further development of their -fork while refusing to upgrade to the stock version of Apache HttpClient citing compatibility -concerns as a reason for such decision. As a result those Android developers who would like to -continue using Apache HttpClient APIs on Android cannot take advantage of newer features, performance -improvements and bug fixes. - -Apache HttpClient 4.3 port for Android is intended to remedy the situation by providing -official releases compatible with Google Android. - - -Differences with the stock version of Apache HttpClient ----------- - -(1) Compiled against HttpClient 4.0 APIs. - -(2) Commons Logging replaced with Android Logging. - -(3) Base64 implementation from Commons Codec replaced with Android Base64. - -(4) Android default SSLSocketFactory used by for SSL/TLS connections. - - -Compatibility notes ----------- - -(1) HttpClient port for Android is compiled against the official Android SDK and is expected -to be fully compatible with any code consuming HttpClient services through its interface -(HttpClient) rather than the default implementation (DefaultHttpClient). - -(2) Code compiled against stock versions of Apache HttpClient 4.3 is not fully compatible with -the HttpClient port for Android. Some of the implementation classes had to be copied (or shaded) -with different names in order to avoid conflicts with the older versions of the same classes -included in the Android runtime. One can increase compatibility with the stock version of -HttpClient by avoiding 'org.apache.http.**.*HC4' classes. diff --git a/lib/httpclient-android/RELEASE_NOTES.txt b/lib/httpclient-android/RELEASE_NOTES.txt deleted file mode 100644 index dde16557..00000000 --- a/lib/httpclient-android/RELEASE_NOTES.txt +++ /dev/null @@ -1,38 +0,0 @@ -Release 4.3.5.1 -------------------- - -This release fixes a number of issues related to Android specific modifications made to -the original HttpClient 4.3.5 code used as a base for the Android port. - -Please note that as of this release HttpClient disables all versions of SSL (including SSLv3) -in favor of the TLS protocol by default. Those users who wish to continue using SSLv3 need -to explicitly enable support for it. - -Users of all versions of Apache HttpClient 4.3 port for Android are advised to upgrade. - - -Changelog -------------------- - -* SSLv3 protocol is disabled by default - Contributed by Oleg Kalnichevski - -* [HTTPCLIENT-1597] Hostname verifiers incorrectly reject certificates with empty attributes - in the certificate subject - Contributed by Oleg Kalnichevski - -* [HTTPCLIENT-1591] Invoke Android specific SNI method via reflection - Contributed by Oleg Kalnichevski - -* [HTTPCLIENT-1566] Fixed broken Base64 encoding in BasicScheme - Contributed by Oleg Kalnichevski - -* [HTTPCLIENT-1554] RequestConfig has no effect when using Android HttpRequest classes. - Contributed by Oleg Kalnichevski - -* [HTTPCLIENT-1555] SSL handshake timeout is always zero (infinite). - Contributed by Oleg Kalnichevski - -* [HTTPCLIENT-1553] Fixed IllegalArgumentException in HttpClientBuilder.build() if system - properties are not used. - Contributed by Oleg Kalnichevski diff --git a/lib/httpclient-android/build.gradle b/lib/httpclient-android/build.gradle deleted file mode 100644 index 032ddfc5..00000000 --- a/lib/httpclient-android/build.gradle +++ /dev/null @@ -1,295 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -buildscript { - repositories { - mavenCentral() - } - dependencies { - classpath 'com.android.tools.build:gradle:1.0.1' - } -} - -apply plugin: 'com.android.library' -apply plugin: 'maven' -apply plugin: 'signing' - -repositories { - mavenCentral() -} - -group = 'org.apache.httpcomponents' -version = HC_VER - -ext.isRelease = !version.endsWith('-SNAPSHOT') - -ext.inceptionYear = '1999' - -android { - - // SDK versions and compileOptions adapted to DAVdroid needs - compileSdkVersion 22 - buildToolsVersion '22.0.1' - - defaultConfig { - minSdkVersion 8 - targetSdkVersion 22 - } - - /*compileOptions { - sourceCompatibility JavaVersion.VERSION_1_5 - targetCompatibility JavaVersion.VERSION_1_5 - }*/ -} - -configurations { - dist -} - -signing { - required { isRelease } -} - -ext.sharedManifest = manifest { - attributes ( - 'Specification-Title': "HttpComponents HttpClient for Android", - 'Specification-Version': "$version", - 'Specification-Vendor': "The Apache Software Foundation", - 'Implementation-Title': "HttpComponents HttpClient for Android", - 'Implementation-Version': "$version", - 'Implementation-Vendor': "The Apache Software Foundation", - 'Implementation-Vendor-Id': "org.apache", - 'url': 'http://hc.apache.org/httpcomponents-client' - ) -} - -android.libraryVariants.all { variant -> - def name = variant.buildType.name - if (name == 'release') { - - task createAndroidJar(type: Jar) { - dependsOn variant.javaCompile - from variant.javaCompile.destinationDir - from 'NOTICE.txt' - from 'LICENSE.txt' - rename '(NOTICE|LICENSE).txt', 'META-INF/$1' - - manifest { - from sharedManifest - } - } - - task createAndroidSrcJar(type: Jar) { - dependsOn variant.javaCompile - from variant.javaCompile.source - from 'NOTICE.txt' - from 'LICENSE.txt' - rename '(NOTICE|LICENSE).txt', 'META-INF/$1' - classifier = 'sources' - - manifest { - from sharedManifest - } - } - - task createAndroidJavadoc(type: Javadoc) { - dependsOn variant.javaCompile - source = variant.javaCompile.source - classpath = files(android.plugin.bootClasspath, variant.javaCompile.classpath.files) - title "Apache HttpClient for Android $HC_VER API" - configure (options) { - docTitle "Apache HttpClient for Android $HC_VER API" - bottom "Copyright © ${inceptionYear}-${Calendar.instance.get(Calendar.YEAR)} " + - "The Apache Software Foundation. " + - "All rights reserved." - } - } - - task createAndroidJavadocJar(type: Jar) { - dependsOn createAndroidJavadoc - from createAndroidJavadoc.destinationDir - from 'NOTICE.txt' - from 'LICENSE.txt' - rename '(NOTICE|LICENSE).txt', 'META-INF/$1' - classifier = 'javadoc' - - manifest { - from sharedManifest - } - } - - artifacts { - dist createAndroidJar - dist createAndroidSrcJar - dist createAndroidJavadocJar - } - - signing { - sign createAndroidJar - sign createAndroidSrcJar - sign createAndroidJavadocJar - } - - artifacts { - tasks.withType(Sign) { Sign task -> - task.signatures.each { PublishArtifact artifact -> - dist artifact - } - } - } - } -} - -// Deployment tasks - -def askPassphrase = { - Console console = System.console() - if (console) { - String password = project.ext.has('signing.password') ? project.ext.'signing.password' : null - String keyId = project.ext.has('signing.keyId') ? project.ext.'signing.keyId' : null - if (keyId && !password) { - char[] raw = console.readPassword("\n> Please provide password for PGP key ${keyId}: ") - project.ext.'signing.password' = new String(raw) - } - } -} - -def askCredentials(MavenDeployer mavenDeployer) { - Console console = System.console() - if (console) { - URL url = new URL(mavenDeployer.repository.url) - def auth = mavenDeployer.repository.authentication - if (auth) { - if (!auth.userName || auth.userName == '') { - String username = console.readLine("\n> Please enter user name for repository '${url}': ") - auth.userName = username - } - if (!auth.password || auth.password == '') { - char[] raw = console.readPassword("\n> Please enter password for repository '${url}': ") - auth.password = new String(raw) - } - } - } -} - -project.ext.archiveSources = copySpec { - from (project.projectDir) { - include 'src/**' - include '*.txt' - include 'build.gradle' - include 'settings.gradle' - include 'gradle.properties' - } -} - -task archiveSrcWin(type: Zip) { - with archiveSources - filter(['eol': org.apache.tools.ant.filters.FixCrLfFilter.CrLf.newInstance('crlf')], - org.apache.tools.ant.filters.FixCrLfFilter) - into "httpcomponents-client-android-$project.version" - classifier = 'src' - baseName = 'httpcomponents-client-android' - version = project.version -} - -task archiveSrcUnix(type: Tar) { - with archiveSources - into "httpcomponents-client-android-$project.version" - filter(['eol': org.apache.tools.ant.filters.FixCrLfFilter.CrLf.newInstance('lf')], - org.apache.tools.ant.filters.FixCrLfFilter) - classifier = 'src' - baseName = 'httpcomponents-client-android' - version = project.version - extension = 'tar.gz' - compression = Compression.GZIP -} - -task uploadDist(type: Upload) { - configuration = configurations.dist - repositories { - mavenDeployer { - def creds = [ - userName: project.ext.has('asf.username') ? project.ext.'asf.username' : null, - password: project.ext.has('asf.password') ? project.ext.'asf.password' : null ] - - if (System.properties['localRepo']) { - repository(url: "file:${buildDir.absolutePath}/repo") - } else { - if (version.endsWith('-SNAPSHOT')) { - repository(url: ASF_SNAPSHOT_REPO) { - authentication(creds) - } - } else { - repository(url: ASF_NEXUS_STAGE) { - authentication(creds) - } - } - } - pom.project { - name 'HttpComponents Client for Android' - url 'http://hc.apache.org/httpcomponents-client/' - organization { - name 'The Apache Software Foundation' - url 'http://www.apache.org/' - } - licenses { - license { - name 'Apache License, Version 2.0' - url 'LICENSE.txt' - distribution 'repo' - } - } - issueManagement { - system 'Jira' - url 'http://issues.apache.org/jira/browse/HTTPCLIENT' - } - } - if (isRelease) { - beforeDeployment { MavenDeployment deployment -> - askPassphrase() - signing.signPom(deployment) - } - } - } - } -} - -gradle.taskGraph.whenReady { TaskExecutionGraph taskGraph -> - taskGraph.allTasks.findAll { Task task -> - task instanceof Upload }.each { Upload task -> - task.doFirst { - task.repositories.each { MavenDeployer mavenDeployer -> - askCredentials(mavenDeployer) - } - } - } - - taskGraph.allTasks.findAll { Task task -> - task instanceof Sign }.each { Sign task -> - task.doFirst { askPassphrase() } - } -} diff --git a/lib/httpclient-android/gradle.properties b/lib/httpclient-android/gradle.properties deleted file mode 100644 index 47d8fbe8..00000000 --- a/lib/httpclient-android/gradle.properties +++ /dev/null @@ -1,3 +0,0 @@ -HC_VER=4.3.5.2-SNAPSHOT -ASF_SNAPSHOT_REPO=https://repository.apache.org/content/repositories/snapshots -ASF_NEXUS_STAGE=https://repository.apache.org/service/local/staging/deploy/maven2 diff --git a/lib/httpclient-android/settings.gradle b/lib/httpclient-android/settings.gradle deleted file mode 100644 index e283a8cd..00000000 --- a/lib/httpclient-android/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'httpclient-android' \ No newline at end of file diff --git a/lib/httpclient-android/src/main/AndroidManifest.xml b/lib/httpclient-android/src/main/AndroidManifest.xml deleted file mode 100644 index adc1e529..00000000 --- a/lib/httpclient-android/src/main/AndroidManifest.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - diff --git a/lib/httpclient-android/src/main/java/org/apache/http/Consts.java b/lib/httpclient-android/src/main/java/org/apache/http/Consts.java deleted file mode 100644 index 6b91055a..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/Consts.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http; - -import java.nio.charset.Charset; - -/** - * Commons constants. - * - * @since 4.2 - */ -public final class Consts { - - public static final int CR = 13; // - public static final int LF = 10; // - public static final int SP = 32; // - public static final int HT = 9; // - - public static final Charset UTF_8 = Charset.forName("UTF-8"); - public static final Charset ASCII = Charset.forName("US-ASCII"); - public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); - - private Consts() { - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/ContentTooLongException.java b/lib/httpclient-android/src/main/java/org/apache/http/ContentTooLongException.java deleted file mode 100644 index f7020ac1..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/ContentTooLongException.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http; - -import java.io.IOException; - -/** - * Signals that HTTP entity content is too long. - * - * @since 4.2 - */ -public class ContentTooLongException extends IOException { - - private static final long serialVersionUID = -924287689552495383L; - - /** - * Creates a new ContentTooLongException with the specified detail message. - * - * @param message exception message - */ - public ContentTooLongException(final String message) { - super(message); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/HttpConnectionFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/HttpConnectionFactory.java deleted file mode 100644 index a8a0749a..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/HttpConnectionFactory.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http; - -import java.io.IOException; -import java.net.Socket; - -/** - * Factory for {@link HttpConnection} instances. - * - * @since 4.3 - */ -public interface HttpConnectionFactory { - - T createConnection(Socket socket) throws IOException; - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/HttpHeaders.java b/lib/httpclient-android/src/main/java/org/apache/http/HttpHeaders.java deleted file mode 100644 index f85384c5..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/HttpHeaders.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http; - -/** - * Constants enumerating the HTTP headers. All headers defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and RFC2518 - * (WebDAV) are listed. - * - * @since 4.1 - */ -public final class HttpHeaders { - - private HttpHeaders() { - } - - /** RFC 2616 (HTTP/1.1) Section 14.1 */ - public static final String ACCEPT = "Accept"; - - /** RFC 2616 (HTTP/1.1) Section 14.2 */ - public static final String ACCEPT_CHARSET = "Accept-Charset"; - - /** RFC 2616 (HTTP/1.1) Section 14.3 */ - public static final String ACCEPT_ENCODING = "Accept-Encoding"; - - /** RFC 2616 (HTTP/1.1) Section 14.4 */ - public static final String ACCEPT_LANGUAGE = "Accept-Language"; - - /** RFC 2616 (HTTP/1.1) Section 14.5 */ - public static final String ACCEPT_RANGES = "Accept-Ranges"; - - /** RFC 2616 (HTTP/1.1) Section 14.6 */ - public static final String AGE = "Age"; - - /** RFC 1945 (HTTP/1.0) Section 10.1, RFC 2616 (HTTP/1.1) Section 14.7 */ - public static final String ALLOW = "Allow"; - - /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */ - public static final String AUTHORIZATION = "Authorization"; - - /** RFC 2616 (HTTP/1.1) Section 14.9 */ - public static final String CACHE_CONTROL = "Cache-Control"; - - /** RFC 2616 (HTTP/1.1) Section 14.10 */ - public static final String CONNECTION = "Connection"; - - /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */ - public static final String CONTENT_ENCODING = "Content-Encoding"; - - /** RFC 2616 (HTTP/1.1) Section 14.12 */ - public static final String CONTENT_LANGUAGE = "Content-Language"; - - /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */ - public static final String CONTENT_LENGTH = "Content-Length"; - - /** RFC 2616 (HTTP/1.1) Section 14.14 */ - public static final String CONTENT_LOCATION = "Content-Location"; - - /** RFC 2616 (HTTP/1.1) Section 14.15 */ - public static final String CONTENT_MD5 = "Content-MD5"; - - /** RFC 2616 (HTTP/1.1) Section 14.16 */ - public static final String CONTENT_RANGE = "Content-Range"; - - /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */ - public static final String CONTENT_TYPE = "Content-Type"; - - /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */ - public static final String DATE = "Date"; - - /** RFC 2518 (WevDAV) Section 9.1 */ - public static final String DAV = "Dav"; - - /** RFC 2518 (WevDAV) Section 9.2 */ - public static final String DEPTH = "Depth"; - - /** RFC 2518 (WevDAV) Section 9.3 */ - public static final String DESTINATION = "Destination"; - - /** RFC 2616 (HTTP/1.1) Section 14.19 */ - public static final String ETAG = "ETag"; - - /** RFC 2616 (HTTP/1.1) Section 14.20 */ - public static final String EXPECT = "Expect"; - - /** RFC 1945 (HTTP/1.0) Section 10.7, RFC 2616 (HTTP/1.1) Section 14.21 */ - public static final String EXPIRES = "Expires"; - - /** RFC 1945 (HTTP/1.0) Section 10.8, RFC 2616 (HTTP/1.1) Section 14.22 */ - public static final String FROM = "From"; - - /** RFC 2616 (HTTP/1.1) Section 14.23 */ - public static final String HOST = "Host"; - - /** RFC 2518 (WevDAV) Section 9.4 */ - public static final String IF = "If"; - - /** RFC 2616 (HTTP/1.1) Section 14.24 */ - public static final String IF_MATCH = "If-Match"; - - /** RFC 1945 (HTTP/1.0) Section 10.9, RFC 2616 (HTTP/1.1) Section 14.25 */ - public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; - - /** RFC 2616 (HTTP/1.1) Section 14.26 */ - public static final String IF_NONE_MATCH = "If-None-Match"; - - /** RFC 2616 (HTTP/1.1) Section 14.27 */ - public static final String IF_RANGE = "If-Range"; - - /** RFC 2616 (HTTP/1.1) Section 14.28 */ - public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; - - /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */ - public static final String LAST_MODIFIED = "Last-Modified"; - - /** RFC 1945 (HTTP/1.0) Section 10.11, RFC 2616 (HTTP/1.1) Section 14.30 */ - public static final String LOCATION = "Location"; - - /** RFC 2518 (WevDAV) Section 9.5 */ - public static final String LOCK_TOKEN = "Lock-Token"; - - /** RFC 2616 (HTTP/1.1) Section 14.31 */ - public static final String MAX_FORWARDS = "Max-Forwards"; - - /** RFC 2518 (WevDAV) Section 9.6 */ - public static final String OVERWRITE = "Overwrite"; - - /** RFC 1945 (HTTP/1.0) Section 10.12, RFC 2616 (HTTP/1.1) Section 14.32 */ - public static final String PRAGMA = "Pragma"; - - /** RFC 2616 (HTTP/1.1) Section 14.33 */ - public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate"; - - /** RFC 2616 (HTTP/1.1) Section 14.34 */ - public static final String PROXY_AUTHORIZATION = "Proxy-Authorization"; - - /** RFC 2616 (HTTP/1.1) Section 14.35 */ - public static final String RANGE = "Range"; - - /** RFC 1945 (HTTP/1.0) Section 10.13, RFC 2616 (HTTP/1.1) Section 14.36 */ - public static final String REFERER = "Referer"; - - /** RFC 2616 (HTTP/1.1) Section 14.37 */ - public static final String RETRY_AFTER = "Retry-After"; - - /** RFC 1945 (HTTP/1.0) Section 10.14, RFC 2616 (HTTP/1.1) Section 14.38 */ - public static final String SERVER = "Server"; - - /** RFC 2518 (WevDAV) Section 9.7 */ - public static final String STATUS_URI = "Status-URI"; - - /** RFC 2616 (HTTP/1.1) Section 14.39 */ - public static final String TE = "TE"; - - /** RFC 2518 (WevDAV) Section 9.8 */ - public static final String TIMEOUT = "Timeout"; - - /** RFC 2616 (HTTP/1.1) Section 14.40 */ - public static final String TRAILER = "Trailer"; - - /** RFC 2616 (HTTP/1.1) Section 14.41 */ - public static final String TRANSFER_ENCODING = "Transfer-Encoding"; - - /** RFC 2616 (HTTP/1.1) Section 14.42 */ - public static final String UPGRADE = "Upgrade"; - - /** RFC 1945 (HTTP/1.0) Section 10.15, RFC 2616 (HTTP/1.1) Section 14.43 */ - public static final String USER_AGENT = "User-Agent"; - - /** RFC 2616 (HTTP/1.1) Section 14.44 */ - public static final String VARY = "Vary"; - - /** RFC 2616 (HTTP/1.1) Section 14.45 */ - public static final String VIA = "Via"; - - /** RFC 2616 (HTTP/1.1) Section 14.46 */ - public static final String WARNING = "Warning"; - - /** RFC 1945 (HTTP/1.0) Section 10.16, RFC 2616 (HTTP/1.1) Section 14.47 */ - public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/MessageConstraintException.java b/lib/httpclient-android/src/main/java/org/apache/http/MessageConstraintException.java deleted file mode 100644 index 2e09ee1b..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/MessageConstraintException.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http; - -import java.io.IOException; - -/** - * Signals a message constraint violation. - * - * @since 4.3 - */ -public class MessageConstraintException extends IOException { - - private static final long serialVersionUID = 6077207720446368695L; - - /** - * Creates a TruncatedChunkException with the specified detail message. - * - * @param message The exception detail message - */ - public MessageConstraintException(final String message) { - super(message); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/TruncatedChunkException.java b/lib/httpclient-android/src/main/java/org/apache/http/TruncatedChunkException.java deleted file mode 100644 index 0458f8e0..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/TruncatedChunkException.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http; - -/** - * Signals a truncated chunk in a chunked stream. - * - * @since 4.1 - */ -public class TruncatedChunkException extends MalformedChunkCodingException { - - private static final long serialVersionUID = -23506263930279460L; - - /** - * Creates a TruncatedChunkException with the specified detail message. - * - * @param message The exception detail message - */ - public TruncatedChunkException(final String message) { - super(message); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/annotation/GuardedBy.java b/lib/httpclient-android/src/main/java/org/apache/http/annotation/GuardedBy.java deleted file mode 100644 index 9e931cb5..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/annotation/GuardedBy.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The field or method to which this annotation is applied can only be accessed - * when holding a particular lock, which may be a built-in (synchronization) lock, - * or may be an explicit java.util.concurrent.Lock. - * - * The argument determines which lock guards the annotated field or method: - *
    - *
  • - * this : The intrinsic lock of the object in whose class the field is defined. - *
  • - *
  • - * class-name.this : For inner classes, it may be necessary to disambiguate 'this'; - * the class-name.this designation allows you to specify which 'this' reference is intended - *
  • - *
  • - * itself : For reference fields only; the object to which the field refers. - *
  • - *
  • - * field-name : The lock object is referenced by the (instance or static) field - * specified by field-name. - *
  • - *
  • - * class-name.field-name : The lock object is reference by the static field specified - * by class-name.field-name. - *
  • - *
  • - * method-name() : The lock object is returned by calling the named nil-ary method. - *
  • - *
  • - * class-name.class : The Class object for the specified class should be used as the lock object. - *
  • - *

    - * Based on code developed by Brian Goetz and Tim Peierls and concepts - * published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls, - * Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. - */ -@Documented -@Target({ElementType.FIELD, ElementType.METHOD}) -@Retention(RetentionPolicy.CLASS) // The original version used RUNTIME -public @interface GuardedBy { - String value(); -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/annotation/Immutable.java b/lib/httpclient-android/src/main/java/org/apache/http/annotation/Immutable.java deleted file mode 100644 index ad08d413..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/annotation/Immutable.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The class to which this annotation is applied is immutable. This means that - * its state cannot be seen to change by callers, which implies that - *

      - *
    • all public fields are final,
    • - *
    • all public final reference fields refer to other immutable objects, and
    • - *
    • constructors and methods do not publish references to any internal state - * which is potentially mutable by the implementation.
    • - *
    - * Immutable objects may still have internal mutable state for purposes of performance - * optimization; some state variables may be lazily computed, so long as they are computed - * from immutable state and that callers cannot tell the difference. - *

    - * Immutable objects are inherently thread-safe; they may be passed between threads or - * published without synchronization. - *

    - * Based on code developed by Brian Goetz and Tim Peierls and concepts - * published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls, - * Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. - */ -@Documented -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.CLASS) // The original version used RUNTIME -public @interface Immutable { -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/annotation/NotThreadSafe.java b/lib/httpclient-android/src/main/java/org/apache/http/annotation/NotThreadSafe.java deleted file mode 100644 index d453d656..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/annotation/NotThreadSafe.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The class to which this annotation is applied is not thread-safe. - * This annotation primarily exists for clarifying the non-thread-safety of a class - * that might otherwise be assumed to be thread-safe, despite the fact that it is a bad - * idea to assume a class is thread-safe without good reason. - * @see ThreadSafe - *

    - * Based on code developed by Brian Goetz and Tim Peierls and concepts - * published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls, - * Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. - */ -@Documented -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.CLASS) // The original version used RUNTIME -public @interface NotThreadSafe { -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/annotation/ThreadSafe.java b/lib/httpclient-android/src/main/java/org/apache/http/annotation/ThreadSafe.java deleted file mode 100644 index 809b99e6..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/annotation/ThreadSafe.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.annotation; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * The class to which this annotation is applied is thread-safe. This means that - * no sequences of accesses (reads and writes to public fields, calls to public methods) - * may put the object into an invalid state, regardless of the interleaving of those actions - * by the runtime, and without requiring any additional synchronization or coordination on the - * part of the caller. - * @see NotThreadSafe - *

    - * Based on code developed by Brian Goetz and Tim Peierls and concepts - * published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls, - * Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. - */ -@Documented -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.CLASS) // The original version used RUNTIME -public @interface ThreadSafe { -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/annotation/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/annotation/package-info.java deleted file mode 100644 index a0d5c861..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/annotation/package-info.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Thread-safety annotations based on JCIP-ANNOTATIONS - *
    - * Copyright (c) 2005 Brian Goetz and Tim Peierls. - * See http://www.jcip.net - */ -package org.apache.http.annotation; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/auth/AuthOption.java b/lib/httpclient-android/src/main/java/org/apache/http/auth/AuthOption.java deleted file mode 100644 index 21f0bc96..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/auth/AuthOption.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.auth; - -import org.apache.http.annotation.Immutable; -import org.apache.http.util.Args; - -/** - * @since 4.2 - */ -@Immutable -public final class AuthOption { - - private final AuthScheme authScheme; - private final Credentials creds; - - public AuthOption(final AuthScheme authScheme, final Credentials creds) { - super(); - Args.notNull(authScheme, "Auth scheme"); - Args.notNull(creds, "User credentials"); - this.authScheme = authScheme; - this.creds = creds; - } - - public AuthScheme getAuthScheme() { - return this.authScheme; - } - - public Credentials getCredentials() { - return this.creds; - } - - @Override - public String toString() { - return this.authScheme.toString(); - } - -} - diff --git a/lib/httpclient-android/src/main/java/org/apache/http/auth/AuthProtocolState.java b/lib/httpclient-android/src/main/java/org/apache/http/auth/AuthProtocolState.java deleted file mode 100644 index fba320c6..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/auth/AuthProtocolState.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.auth; - -public enum AuthProtocolState { - - UNCHALLENGED, CHALLENGED, HANDSHAKE, FAILURE, SUCCESS - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/auth/AuthSchemeProvider.java b/lib/httpclient-android/src/main/java/org/apache/http/auth/AuthSchemeProvider.java deleted file mode 100644 index 572a8dd4..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/auth/AuthSchemeProvider.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.auth; - -import org.apache.http.protocol.HttpContext; - -/** - * Factory for {@link AuthScheme} implementations. - * - * @since 4.3 - */ -public interface AuthSchemeProvider { - - /** - * Creates an instance of {@link AuthScheme}. - * - * @return auth scheme. - */ - AuthScheme create(HttpContext context); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/auth/AuthStateHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/auth/AuthStateHC4.java deleted file mode 100644 index caef2e2c..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/auth/AuthStateHC4.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.auth; - -import java.util.Queue; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.util.Args; - -/** - * This class provides detailed information about the state of the authentication process. - * - * @since 4.0 - */ -@NotThreadSafe -public class AuthStateHC4 { - - /** Actual state of authentication protocol */ - private AuthProtocolState state; - - /** Actual authentication scheme */ - private AuthScheme authScheme; - - /** Actual authentication scope */ - private AuthScope authScope; - - /** Credentials selected for authentication */ - private Credentials credentials; - - /** Available auth options */ - private Queue authOptions; - - public AuthStateHC4() { - super(); - this.state = AuthProtocolState.UNCHALLENGED; - } - - /** - * Resets the auth state. - * - * @since 4.2 - */ - public void reset() { - this.state = AuthProtocolState.UNCHALLENGED; - this.authOptions = null; - this.authScheme = null; - this.authScope = null; - this.credentials = null; - } - - /** - * @since 4.2 - */ - public AuthProtocolState getState() { - return this.state; - } - - /** - * @since 4.2 - */ - public void setState(final AuthProtocolState state) { - this.state = state != null ? state : AuthProtocolState.UNCHALLENGED; - } - - /** - * Returns actual {@link AuthScheme}. May be null. - */ - public AuthScheme getAuthScheme() { - return this.authScheme; - } - - /** - * Returns actual {@link Credentials}. May be null. - */ - public Credentials getCredentials() { - return this.credentials; - } - - /** - * Updates the auth state with {@link AuthScheme} and {@link Credentials}. - * - * @param authScheme auth scheme. May not be null. - * @param credentials user crednetials. May not be null. - * - * @since 4.2 - */ - public void update(final AuthScheme authScheme, final Credentials credentials) { - Args.notNull(authScheme, "Auth scheme"); - Args.notNull(credentials, "Credentials"); - this.authScheme = authScheme; - this.credentials = credentials; - this.authOptions = null; - } - - /** - * Returns available {@link AuthOption}s. May be null. - * - * @since 4.2 - */ - public Queue getAuthOptions() { - return this.authOptions; - } - - /** - * Returns true if {@link AuthOption}s are available, false - * otherwise. - * - * @since 4.2 - */ - public boolean hasAuthOptions() { - return this.authOptions != null && !this.authOptions.isEmpty(); - } - - /** - * Updates the auth state with a queue of {@link AuthOption}s. - * - * @param authOptions a queue of auth options. May not be null or empty. - * - * @since 4.2 - */ - public void update(final Queue authOptions) { - Args.notEmpty(authOptions, "Queue of auth options"); - this.authOptions = authOptions; - this.authScheme = null; - this.credentials = null; - } - - /** - * Invalidates the authentication state by resetting its parameters. - * - * @deprecated (4.2) use {@link #reset()} - */ - @Deprecated - public void invalidate() { - reset(); - } - - /** - * @deprecated (4.2) do not use - */ - @Deprecated - public boolean isValid() { - return this.authScheme != null; - } - - /** - * Assigns the given {@link AuthScheme authentication scheme}. - * - * @param authScheme the {@link AuthScheme authentication scheme} - * - * @deprecated (4.2) use {@link #update(AuthScheme, Credentials)} - */ - @Deprecated - public void setAuthScheme(final AuthScheme authScheme) { - if (authScheme == null) { - reset(); - return; - } - this.authScheme = authScheme; - } - - /** - * Sets user {@link Credentials} to be used for authentication - * - * @param credentials User credentials - * - * @deprecated (4.2) use {@link #update(AuthScheme, Credentials)} - */ - @Deprecated - public void setCredentials(final Credentials credentials) { - this.credentials = credentials; - } - - /** - * Returns actual {@link AuthScope} if available - * - * @return actual authentication scope if available, null. - * - */ -package org.apache.http.auth; - -/** - * Challenge mode (TARGET or PROXY) - * - * @since 4.2 - */ -public enum ChallengeState { - - TARGET, PROXY - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/auth/ContextAwareAuthScheme.java b/lib/httpclient-android/src/main/java/org/apache/http/auth/ContextAwareAuthScheme.java deleted file mode 100644 index 0571fcf5..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/auth/ContextAwareAuthScheme.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.auth; - -import org.apache.http.Header; -import org.apache.http.HttpRequest; -import org.apache.http.protocol.HttpContext; - -/** - * This interface represents an extended authentication scheme - * that requires access to {@link HttpContext} in order to - * generate an authorization string. - * - * TODO: Fix AuthScheme interface in the next major version - * - * @since 4.1 - */ - -public interface ContextAwareAuthScheme extends AuthScheme { - - /** - * Produces an authorization string for the given set of - * {@link Credentials}. - * - * @param credentials The set of credentials to be used for athentication - * @param request The request being authenticated - * @param context HTTP context - * @throws AuthenticationException if authorization string cannot - * be generated due to an authentication failure - * - * @return the authorization string - */ - Header authenticate( - Credentials credentials, - HttpRequest request, - HttpContext context) throws AuthenticationException; - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/auth/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/auth/package-info.java deleted file mode 100644 index 801f9324..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/auth/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Client HTTP authentication APIs. - */ -package org.apache.http.auth; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/auth/params/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/auth/params/package-info.java deleted file mode 100644 index 73399dc4..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/auth/params/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Deprecated. - * @deprecated (4.3). - */ -package org.apache.http.auth.params; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/AuthCache.java b/lib/httpclient-android/src/main/java/org/apache/http/client/AuthCache.java deleted file mode 100644 index 26c0b88c..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/AuthCache.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client; - -import org.apache.http.HttpHost; -import org.apache.http.auth.AuthScheme; - -/** - * Abstract {@link AuthScheme} cache. Initialized {@link AuthScheme} objects - * from this cache can be used to preemptively authenticate against known - * hosts. - * - * @since 4.1 - */ -public interface AuthCache { - - void put(HttpHost host, AuthScheme authScheme); - - AuthScheme get(HttpHost host); - - void remove(HttpHost host); - - void clear(); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/AuthenticationStrategy.java b/lib/httpclient-android/src/main/java/org/apache/http/client/AuthenticationStrategy.java deleted file mode 100644 index 4f4ef969..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/AuthenticationStrategy.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client; - -import java.util.Map; -import java.util.Queue; - -import org.apache.http.Header; -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.auth.AuthOption; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.protocol.HttpContext; - -/** -/** - * A handler for determining if an HTTP response represents an authentication challenge that was - * sent back to the client as a result of authentication failure. - *

    - * Implementations of this interface must be thread-safe. Access to shared data must be - * synchronized as methods of this interface may be executed from multiple threads. - * - * @since 4.2 - */ -public interface AuthenticationStrategy { - - /** - * Determines if the given HTTP response response represents - * an authentication challenge that was sent back as a result - * of authentication failure. - * - * @param authhost authentication host. - * @param response HTTP response. - * @param context HTTP context. - * @return true if user authentication is required, - * false otherwise. - */ - boolean isAuthenticationRequested( - HttpHost authhost, - HttpResponse response, - HttpContext context); - - /** - * Extracts from the given HTTP response a collection of authentication - * challenges, each of which represents an authentication scheme supported - * by the authentication host. - * - * @param authhost authentication host. - * @param response HTTP response. - * @param context HTTP context. - * @return a collection of challenges keyed by names of corresponding - * authentication schemes. - * @throws MalformedChallengeException if one of the authentication - * challenges is not valid or malformed. - */ - Map getChallenges( - HttpHost authhost, - HttpResponse response, - HttpContext context) throws MalformedChallengeException; - - /** - * Selects one authentication challenge out of all available and - * creates and generates {@link AuthOption} instance capable of - * processing that challenge. - * - * @param challenges collection of challenges. - * @param authhost authentication host. - * @param response HTTP response. - * @param context HTTP context. - * @return authentication auth schemes that can be used for authentication. Can be empty. - * @throws MalformedChallengeException if one of the authentication - * challenges is not valid or malformed. - */ - Queue select( - Map challenges, - HttpHost authhost, - HttpResponse response, - HttpContext context) throws MalformedChallengeException; - - /** - * Callback invoked in case of successful authentication. - * - * @param authhost authentication host. - * @param authScheme authentication scheme used. - * @param context HTTP context. - */ - void authSucceeded( - HttpHost authhost, - AuthScheme authScheme, - HttpContext context); - - /** - * Callback invoked in case of unsuccessful authentication. - * - * @param authhost authentication host. - * @param authScheme authentication scheme used. - * @param context HTTP context. - */ - void authFailed( - HttpHost authhost, - AuthScheme authScheme, - HttpContext context); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/BackoffManager.java b/lib/httpclient-android/src/main/java/org/apache/http/client/BackoffManager.java deleted file mode 100644 index d79b9fb5..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/BackoffManager.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client; - -import org.apache.http.conn.routing.HttpRoute; - -/** - * Represents a controller that dynamically adjusts the size - * of an available connection pool based on feedback from - * using the connections. - * - * @since 4.2 - * - */ -public interface BackoffManager { - - /** - * Called when we have decided that the result of - * using a connection should be interpreted as a - * backoff signal. - */ - public void backOff(HttpRoute route); - - /** - * Called when we have determined that the result of - * using a connection has succeeded and that we may - * probe for more connections. - */ - public void probe(HttpRoute route); -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/ConnectionBackoffStrategy.java b/lib/httpclient-android/src/main/java/org/apache/http/client/ConnectionBackoffStrategy.java deleted file mode 100644 index b71068b9..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/ConnectionBackoffStrategy.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client; - -import org.apache.http.HttpResponse; - -/** - * When managing a dynamic number of connections for a given route, this - * strategy assesses whether a given request execution outcome should - * result in a backoff signal or not, based on either examining the - * Throwable that resulted or by examining the resulting - * response (e.g. for its status code). - * - * @since 4.2 - * - */ -public interface ConnectionBackoffStrategy { - - /** - * Determines whether seeing the given Throwable as - * a result of request execution should result in a backoff - * signal. - * @param t the Throwable that happened - * @return true if a backoff signal should be - * given - */ - boolean shouldBackoff(Throwable t); - - /** - * Determines whether receiving the given {@link HttpResponse} as - * a result of request execution should result in a backoff - * signal. Implementations MUST restrict themselves to examining - * the response header and MUST NOT consume any of the response - * body, if any. - * @param resp the HttpResponse that was received - * @return true if a backoff signal should be - * given - */ - boolean shouldBackoff(HttpResponse resp); -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/RedirectStrategy.java b/lib/httpclient-android/src/main/java/org/apache/http/client/RedirectStrategy.java deleted file mode 100644 index 9a824697..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/RedirectStrategy.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client; - -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.ProtocolException; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.protocol.HttpContext; - -/** - * A strategy for determining if an HTTP request should be redirected to - * a new location in response to an HTTP response received from the target - * server. - *

    - * Implementations of this interface must be thread-safe. Access to shared - * data must be synchronized as methods of this interface may be executed - * from multiple threads. - * - * @since 4.1 - */ -public interface RedirectStrategy { - - /** - * Determines if a request should be redirected to a new location - * given the response from the target server. - * - * @param request the executed request - * @param response the response received from the target server - * @param context the context for the request execution - * - * @return true if the request should be redirected, false - * otherwise - */ - boolean isRedirected( - HttpRequest request, - HttpResponse response, - HttpContext context) throws ProtocolException; - - /** - * Determines the redirect location given the response from the target - * server and the current request execution context and generates a new - * request to be sent to the location. - * - * @param request the executed request - * @param response the response received from the target server - * @param context the context for the request execution - * - * @return redirected request - */ - HttpUriRequest getRedirect( - HttpRequest request, - HttpResponse response, - HttpContext context) throws ProtocolException; - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/ServiceUnavailableRetryStrategy.java b/lib/httpclient-android/src/main/java/org/apache/http/client/ServiceUnavailableRetryStrategy.java deleted file mode 100644 index 69c449ff..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/ServiceUnavailableRetryStrategy.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client; - -import org.apache.http.HttpResponse; -import org.apache.http.protocol.HttpContext; - -/** - * Strategy interface that allows API users to plug in their own logic to - * control whether or not a retry should automatically be done, how many times - * it should be retried and so on. - * - * @since 4.2 - */ -public interface ServiceUnavailableRetryStrategy { - - /** - * Determines if a method should be retried given the response from the target server. - * - * @param response the response from the target server - * @param executionCount the number of times this method has been - * unsuccessfully executed - * @param context the context for the request execution - - * @return true if the method should be retried, false - * otherwise - */ - boolean retryRequest(HttpResponse response, int executionCount, HttpContext context); - - /** - * @return The interval between the subsequent auto-retries. - */ - long getRetryInterval(); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/config/AuthSchemes.java b/lib/httpclient-android/src/main/java/org/apache/http/client/config/AuthSchemes.java deleted file mode 100644 index 3b6d803f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/config/AuthSchemes.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.config; - -import org.apache.http.annotation.Immutable; - -/** - * Standard authentication schemes supported by HttpClient. - * - * @since 4.3 - */ -@Immutable -public final class AuthSchemes { - - /** - * Basic authentication scheme as defined in RFC2617 (considered inherently - * insecure, but most widely supported) - */ - public static final String BASIC = "Basic"; - - /** - * Digest authentication scheme as defined in RFC2617. - */ - public static final String DIGEST = "Digest"; - - /** - * The NTLM scheme is a proprietary Microsoft Windows Authentication - * protocol (considered to be the most secure among currently supported - * authentication schemes). - */ - public static final String NTLM = "NTLM"; - - /** - * SPNEGO Authentication scheme. - */ - public static final String SPNEGO = "negotiate"; - - /** - * Kerberos Authentication scheme. - */ - public static final String KERBEROS = "Kerberos"; - - private AuthSchemes() { - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/config/CookieSpecs.java b/lib/httpclient-android/src/main/java/org/apache/http/client/config/CookieSpecs.java deleted file mode 100644 index 4ab3ddd1..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/config/CookieSpecs.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.config; - -import org.apache.http.annotation.Immutable; - -/** - * Standard cookie specifications supported by HttpClient. - * - * @since 4.3 - */ -@Immutable -public final class CookieSpecs { - - /** - * The policy that provides high degree of compatibility - * with common cookie management of popular HTTP agents. - */ - public static final String BROWSER_COMPATIBILITY = "compatibility"; - - /** - * The Netscape cookie draft compliant policy. - */ - public static final String NETSCAPE = "netscape"; - - /** - * The RFC 2965 compliant policy (standard). - */ - public static final String STANDARD = "standard"; - - /** - * The default 'best match' policy. - */ - public static final String BEST_MATCH = "best-match"; - - /** - * The policy that ignores cookies. - */ - public static final String IGNORE_COOKIES = "ignoreCookies"; - - private CookieSpecs() { - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/config/RequestConfig.java b/lib/httpclient-android/src/main/java/org/apache/http/client/config/RequestConfig.java deleted file mode 100644 index 9bb457d4..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/config/RequestConfig.java +++ /dev/null @@ -1,442 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.config; - -import java.net.InetAddress; -import java.util.Collection; - -import org.apache.http.HttpHost; - -public class RequestConfig implements Cloneable { - - public static final RequestConfig DEFAULT = new Builder().build(); - - private final boolean expectContinueEnabled; - private final HttpHost proxy; - private final InetAddress localAddress; - private final boolean staleConnectionCheckEnabled; - private final String cookieSpec; - private final boolean redirectsEnabled; - private final boolean relativeRedirectsAllowed; - private final boolean circularRedirectsAllowed; - private final int maxRedirects; - private final boolean authenticationEnabled; - private final Collection targetPreferredAuthSchemes; - private final Collection proxyPreferredAuthSchemes; - private final int connectionRequestTimeout; - private final int connectTimeout; - private final int socketTimeout; - - RequestConfig( - final boolean expectContinueEnabled, - final HttpHost proxy, - final InetAddress localAddress, - final boolean staleConnectionCheckEnabled, - final String cookieSpec, - final boolean redirectsEnabled, - final boolean relativeRedirectsAllowed, - final boolean circularRedirectsAllowed, - final int maxRedirects, - final boolean authenticationEnabled, - final Collection targetPreferredAuthSchemes, - final Collection proxyPreferredAuthSchemes, - final int connectionRequestTimeout, - final int connectTimeout, - final int socketTimeout) { - super(); - this.expectContinueEnabled = expectContinueEnabled; - this.proxy = proxy; - this.localAddress = localAddress; - this.staleConnectionCheckEnabled = staleConnectionCheckEnabled; - this.cookieSpec = cookieSpec; - this.redirectsEnabled = redirectsEnabled; - this.relativeRedirectsAllowed = relativeRedirectsAllowed; - this.circularRedirectsAllowed = circularRedirectsAllowed; - this.maxRedirects = maxRedirects; - this.authenticationEnabled = authenticationEnabled; - this.targetPreferredAuthSchemes = targetPreferredAuthSchemes; - this.proxyPreferredAuthSchemes = proxyPreferredAuthSchemes; - this.connectionRequestTimeout = connectionRequestTimeout; - this.connectTimeout = connectTimeout; - this.socketTimeout = socketTimeout; - } - - /** - * Determines whether the 'Expect: 100-Continue' handshake is enabled - * for entity enclosing methods. The purpose of the 'Expect: 100-Continue' - * handshake is to allow a client that is sending a request message with - * a request body to determine if the origin server is willing to - * accept the request (based on the request headers) before the client - * sends the request body. - *

    - * The use of the 'Expect: 100-continue' handshake can result in - * a noticeable performance improvement for entity enclosing requests - * (such as POST and PUT) that require the target server's - * authentication. - *

    - * 'Expect: 100-continue' handshake should be used with caution, as it - * may cause problems with HTTP servers and proxies that do not support - * HTTP/1.1 protocol. - *

    - * Default: false - */ - public boolean isExpectContinueEnabled() { - return expectContinueEnabled; - } - - /** - * Returns HTTP proxy to be used for request execution. - *

    - * Default: null - */ - public HttpHost getProxy() { - return proxy; - } - - /** - * Returns local address to be used for request execution. - *

    - * On machines with multiple network interfaces, this parameter - * can be used to select the network interface from which the - * connection originates. - *

    - * Default: null - */ - public InetAddress getLocalAddress() { - return localAddress; - } - - /** - * Determines whether stale connection check is to be used. The stale - * connection check can cause up to 30 millisecond overhead per request and - * should be used only when appropriate. For performance critical - * operations this check should be disabled. - *

    - * Default: true - */ - public boolean isStaleConnectionCheckEnabled() { - return staleConnectionCheckEnabled; - } - - /** - * Determines the name of the cookie specification to be used for HTTP state - * management. - *

    - * Default: null - */ - public String getCookieSpec() { - return cookieSpec; - } - - /** - * Determines whether redirects should be handled automatically. - *

    - * Default: true - */ - public boolean isRedirectsEnabled() { - return redirectsEnabled; - } - - /** - * Determines whether relative redirects should be rejected. HTTP specification - * requires the location value be an absolute URI. - *

    - * Default: true - */ - public boolean isRelativeRedirectsAllowed() { - return relativeRedirectsAllowed; - } - - /** - * Determines whether circular redirects (redirects to the same location) should - * be allowed. The HTTP spec is not sufficiently clear whether circular redirects - * are permitted, therefore optionally they can be enabled - *

    - * Default: false - */ - public boolean isCircularRedirectsAllowed() { - return circularRedirectsAllowed; - } - - /** - * Returns the maximum number of redirects to be followed. The limit on number - * of redirects is intended to prevent infinite loops. - *

    - * Default: 50 - */ - public int getMaxRedirects() { - return maxRedirects; - } - - /** - * Determines whether authentication should be handled automatically. - *

    - * Default: true - */ - public boolean isAuthenticationEnabled() { - return authenticationEnabled; - } - - /** - * Determines the order of preference for supported authentication schemes - * when authenticating with the target host. - *

    - * Default: null - */ - public Collection getTargetPreferredAuthSchemes() { - return targetPreferredAuthSchemes; - } - - /** - * Determines the order of preference for supported authentication schemes - * when authenticating with the proxy host. - *

    - * Default: null - */ - public Collection getProxyPreferredAuthSchemes() { - return proxyPreferredAuthSchemes; - } - - /** - * Returns the timeout in milliseconds used when requesting a connection - * from the connection manager. A timeout value of zero is interpreted - * as an infinite timeout. - *

    - * A timeout value of zero is interpreted as an infinite timeout. - * A negative value is interpreted as undefined (system default). - *

    - * Default: -1 - */ - public int getConnectionRequestTimeout() { - return connectionRequestTimeout; - } - - /** - * Determines the timeout in milliseconds until a connection is established. - * A timeout value of zero is interpreted as an infinite timeout. - *

    - * A timeout value of zero is interpreted as an infinite timeout. - * A negative value is interpreted as undefined (system default). - *

    - * Default: -1 - */ - public int getConnectTimeout() { - return connectTimeout; - } - - /** - * Defines the socket timeout (SO_TIMEOUT) in milliseconds, - * which is the timeout for waiting for data or, put differently, - * a maximum period inactivity between two consecutive data packets). - *

    - * A timeout value of zero is interpreted as an infinite timeout. - * A negative value is interpreted as undefined (system default). - *

    - * Default: -1 - */ - public int getSocketTimeout() { - return socketTimeout; - } - - @Override - protected RequestConfig clone() throws CloneNotSupportedException { - return (RequestConfig) super.clone(); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append(", expectContinueEnabled=").append(expectContinueEnabled); - builder.append(", proxy=").append(proxy); - builder.append(", localAddress=").append(localAddress); - builder.append(", staleConnectionCheckEnabled=").append(staleConnectionCheckEnabled); - builder.append(", cookieSpec=").append(cookieSpec); - builder.append(", redirectsEnabled=").append(redirectsEnabled); - builder.append(", relativeRedirectsAllowed=").append(relativeRedirectsAllowed); - builder.append(", maxRedirects=").append(maxRedirects); - builder.append(", circularRedirectsAllowed=").append(circularRedirectsAllowed); - builder.append(", authenticationEnabled=").append(authenticationEnabled); - builder.append(", targetPreferredAuthSchemes=").append(targetPreferredAuthSchemes); - builder.append(", proxyPreferredAuthSchemes=").append(proxyPreferredAuthSchemes); - builder.append(", connectionRequestTimeout=").append(connectionRequestTimeout); - builder.append(", connectTimeout=").append(connectTimeout); - builder.append(", socketTimeout=").append(socketTimeout); - builder.append("]"); - return builder.toString(); - } - - public static RequestConfig.Builder custom() { - return new Builder(); - } - - public static RequestConfig.Builder copy(final RequestConfig config) { - return new Builder() - .setExpectContinueEnabled(config.isExpectContinueEnabled()) - .setProxy(config.getProxy()) - .setLocalAddress(config.getLocalAddress()) - .setStaleConnectionCheckEnabled(config.isStaleConnectionCheckEnabled()) - .setCookieSpec(config.getCookieSpec()) - .setRedirectsEnabled(config.isRedirectsEnabled()) - .setRelativeRedirectsAllowed(config.isRelativeRedirectsAllowed()) - .setCircularRedirectsAllowed(config.isCircularRedirectsAllowed()) - .setMaxRedirects(config.getMaxRedirects()) - .setAuthenticationEnabled(config.isAuthenticationEnabled()) - .setTargetPreferredAuthSchemes(config.getTargetPreferredAuthSchemes()) - .setProxyPreferredAuthSchemes(config.getProxyPreferredAuthSchemes()) - .setConnectionRequestTimeout(config.getConnectionRequestTimeout()) - .setConnectTimeout(config.getConnectTimeout()) - .setSocketTimeout(config.getSocketTimeout()); - } - - public static class Builder { - - private boolean expectContinueEnabled; - private HttpHost proxy; - private InetAddress localAddress; - private boolean staleConnectionCheckEnabled; - private String cookieSpec; - private boolean redirectsEnabled; - private boolean relativeRedirectsAllowed; - private boolean circularRedirectsAllowed; - private int maxRedirects; - private boolean authenticationEnabled; - private Collection targetPreferredAuthSchemes; - private Collection proxyPreferredAuthSchemes; - private int connectionRequestTimeout; - private int connectTimeout; - private int socketTimeout; - - Builder() { - super(); - this.staleConnectionCheckEnabled = true; - this.redirectsEnabled = true; - this.maxRedirects = 50; - this.relativeRedirectsAllowed = true; - this.authenticationEnabled = true; - this.connectionRequestTimeout = -1; - this.connectTimeout = -1; - this.socketTimeout = -1; - } - - public Builder setExpectContinueEnabled(final boolean expectContinueEnabled) { - this.expectContinueEnabled = expectContinueEnabled; - return this; - } - - public Builder setProxy(final HttpHost proxy) { - this.proxy = proxy; - return this; - } - - public Builder setLocalAddress(final InetAddress localAddress) { - this.localAddress = localAddress; - return this; - } - - public Builder setStaleConnectionCheckEnabled(final boolean staleConnectionCheckEnabled) { - this.staleConnectionCheckEnabled = staleConnectionCheckEnabled; - return this; - } - - public Builder setCookieSpec(final String cookieSpec) { - this.cookieSpec = cookieSpec; - return this; - } - - public Builder setRedirectsEnabled(final boolean redirectsEnabled) { - this.redirectsEnabled = redirectsEnabled; - return this; - } - - public Builder setRelativeRedirectsAllowed(final boolean relativeRedirectsAllowed) { - this.relativeRedirectsAllowed = relativeRedirectsAllowed; - return this; - } - - public Builder setCircularRedirectsAllowed(final boolean circularRedirectsAllowed) { - this.circularRedirectsAllowed = circularRedirectsAllowed; - return this; - } - - public Builder setMaxRedirects(final int maxRedirects) { - this.maxRedirects = maxRedirects; - return this; - } - - public Builder setAuthenticationEnabled(final boolean authenticationEnabled) { - this.authenticationEnabled = authenticationEnabled; - return this; - } - - public Builder setTargetPreferredAuthSchemes(final Collection targetPreferredAuthSchemes) { - this.targetPreferredAuthSchemes = targetPreferredAuthSchemes; - return this; - } - - public Builder setProxyPreferredAuthSchemes(final Collection proxyPreferredAuthSchemes) { - this.proxyPreferredAuthSchemes = proxyPreferredAuthSchemes; - return this; - } - - public Builder setConnectionRequestTimeout(final int connectionRequestTimeout) { - this.connectionRequestTimeout = connectionRequestTimeout; - return this; - } - - public Builder setConnectTimeout(final int connectTimeout) { - this.connectTimeout = connectTimeout; - return this; - } - - public Builder setSocketTimeout(final int socketTimeout) { - this.socketTimeout = socketTimeout; - return this; - } - - public RequestConfig build() { - return new RequestConfig( - expectContinueEnabled, - proxy, - localAddress, - staleConnectionCheckEnabled, - cookieSpec, - redirectsEnabled, - relativeRedirectsAllowed, - circularRedirectsAllowed, - maxRedirects, - authenticationEnabled, - targetPreferredAuthSchemes, - proxyPreferredAuthSchemes, - connectionRequestTimeout, - connectTimeout, - socketTimeout); - } - - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/config/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/client/config/package-info.java deleted file mode 100644 index 78bd81b4..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/config/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Client configuration APIs. - */ -package org.apache.http.client.config; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/DecompressingEntity.java b/lib/httpclient-android/src/main/java/org/apache/http/client/entity/DecompressingEntity.java deleted file mode 100644 index 90b37287..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/DecompressingEntity.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.entity; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.http.HttpEntity; -import org.apache.http.entity.HttpEntityWrapperHC4; -import org.apache.http.util.Args; - -/** - * Common base class for decompressing {@link HttpEntity} implementations. - * - * @since 4.1 - */ -abstract class DecompressingEntity extends HttpEntityWrapperHC4 { - - /** - * Default buffer size. - */ - private static final int BUFFER_SIZE = 1024 * 2; - - /** - * {@link #getContent()} method must return the same {@link InputStream} - * instance when DecompressingEntity is wrapping a streaming entity. - */ - private InputStream content; - - /** - * Creates a new {@link DecompressingEntity}. - * - * @param wrapped - * the non-null {@link HttpEntity} to be wrapped - */ - public DecompressingEntity(final HttpEntity wrapped) { - super(wrapped); - } - - abstract InputStream decorate(final InputStream wrapped) throws IOException; - - private InputStream getDecompressingStream() throws IOException { - final InputStream in = wrappedEntity.getContent(); - return new LazyDecompressingInputStream(in, this); - } - - /** - * {@inheritDoc} - */ - @Override - public InputStream getContent() throws IOException { - if (wrappedEntity.isStreaming()) { - if (content == null) { - content = getDecompressingStream(); - } - return content; - } else { - return getDecompressingStream(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - final InputStream instream = getContent(); - try { - final byte[] buffer = new byte[BUFFER_SIZE]; - int l; - while ((l = instream.read(buffer)) != -1) { - outstream.write(buffer, 0, l); - } - } finally { - instream.close(); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/DeflateDecompressingEntity.java b/lib/httpclient-android/src/main/java/org/apache/http/client/entity/DeflateDecompressingEntity.java deleted file mode 100644 index 5b0136f5..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/DeflateDecompressingEntity.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.entity; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; - -/** - * {@link org.apache.http.entity.HttpEntityWrapper} responsible for handling - * deflate Content Coded responses. In RFC2616 terms, deflate - * means a zlib stream as defined in RFC1950. Some server - * implementations have misinterpreted RFC2616 to mean that a - * deflate stream as defined in RFC1951 should be used - * (or maybe they did that since that's how IE behaves?). It's confusing - * that deflate in HTTP 1.1 means zlib streams - * rather than deflate streams. We handle both types in here, - * since that's what is seen on the internet. Moral - prefer - * gzip! - * - * @see GzipDecompressingEntity - * - * @since 4.1 - */ -public class DeflateDecompressingEntity extends DecompressingEntity { - - /** - * Creates a new {@link DeflateDecompressingEntity} which will wrap the specified - * {@link HttpEntity}. - * - * @param entity - * a non-null {@link HttpEntity} to be wrapped - */ - public DeflateDecompressingEntity(final HttpEntity entity) { - super(entity); - } - - /** - * Returns the non-null InputStream that should be returned to by all requests to - * {@link #getContent()}. - * - * @return a non-null InputStream - * @throws IOException if there was a problem - */ - @Override - InputStream decorate(final InputStream wrapped) throws IOException { - return new DeflateInputStream(wrapped); - } - - /** - * {@inheritDoc} - */ - @Override - public Header getContentEncoding() { - - /* This HttpEntityWrapperHC4 has dealt with the Content-Encoding. */ - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public long getContentLength() { - - /* Length of inflated content is unknown. */ - return -1; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/DeflateInputStream.java b/lib/httpclient-android/src/main/java/org/apache/http/client/entity/DeflateInputStream.java deleted file mode 100644 index dfd8f4be..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/DeflateInputStream.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.entity; - -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; -import java.util.zip.DataFormatException; -import java.util.zip.Inflater; -import java.util.zip.InflaterInputStream; - -/** Deflate input stream. This class includes logic needed for various Rfc's in order -* to reasonably implement the "deflate" compression style. -*/ -public class DeflateInputStream extends InputStream -{ - private InputStream sourceStream; - - public DeflateInputStream(final InputStream wrapped) - throws IOException - { - /* - * A zlib stream will have a header. - * - * CMF | FLG [| DICTID ] | ...compressed data | ADLER32 | - * - * * CMF is one byte. - * - * * FLG is one byte. - * - * * DICTID is four bytes, and only present if FLG.FDICT is set. - * - * Sniff the content. Does it look like a zlib stream, with a CMF, etc? c.f. RFC1950, - * section 2.2. http://tools.ietf.org/html/rfc1950#page-4 - * - * We need to see if it looks like a proper zlib stream, or whether it is just a deflate - * stream. RFC2616 calls zlib streams deflate. Confusing, isn't it? That's why some servers - * implement deflate Content-Encoding using deflate streams, rather than zlib streams. - * - * We could start looking at the bytes, but to be honest, someone else has already read - * the RFCs and implemented that for us. So we'll just use the JDK libraries and exception - * handling to do this. If that proves slow, then we could potentially change this to check - * the first byte - does it look like a CMF? What about the second byte - does it look like - * a FLG, etc. - */ - - /* We read a small buffer to sniff the content. */ - final byte[] peeked = new byte[6]; - - final PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length); - - final int headerLength = pushback.read(peeked); - - if (headerLength == -1) { - throw new IOException("Unable to read the response"); - } - - /* We try to read the first uncompressed byte. */ - final byte[] dummy = new byte[1]; - - final Inflater inf = new Inflater(); - - try { - int n; - while ((n = inf.inflate(dummy)) == 0) { - if (inf.finished()) { - - /* Not expecting this, so fail loudly. */ - throw new IOException("Unable to read the response"); - } - - if (inf.needsDictionary()) { - - /* Need dictionary - then it must be zlib stream with DICTID part? */ - break; - } - - if (inf.needsInput()) { - inf.setInput(peeked); - } - } - - if (n == -1) { - throw new IOException("Unable to read the response"); - } - - /* - * We read something without a problem, so it's a valid zlib stream. Just need to reset - * and return an unused InputStream now. - */ - pushback.unread(peeked, 0, headerLength); - sourceStream = new DeflateStream(pushback, new Inflater()); - } catch (final DataFormatException e) { - - /* Presume that it's an RFC1951 deflate stream rather than RFC1950 zlib stream and try - * again. */ - pushback.unread(peeked, 0, headerLength); - sourceStream = new DeflateStream(pushback, new Inflater(true)); - } finally { - inf.end(); - } - - } - - /** Read a byte. - */ - @Override - public int read() - throws IOException - { - return sourceStream.read(); - } - - /** Read lots of bytes. - */ - @Override - public int read(final byte[] b) - throws IOException - { - return sourceStream.read(b); - } - - /** Read lots of specific bytes. - */ - @Override - public int read(final byte[] b, final int off, final int len) - throws IOException - { - return sourceStream.read(b,off,len); - } - - /** Skip - */ - @Override - public long skip(final long n) - throws IOException - { - return sourceStream.skip(n); - } - - /** Get available. - */ - @Override - public int available() - throws IOException - { - return sourceStream.available(); - } - - /** Mark. - */ - @Override - public void mark(final int readLimit) - { - sourceStream.mark(readLimit); - } - - /** Reset. - */ - @Override - public void reset() - throws IOException - { - sourceStream.reset(); - } - - /** Check if mark is supported. - */ - @Override - public boolean markSupported() - { - return sourceStream.markSupported(); - } - - /** Close. - */ - @Override - public void close() - throws IOException - { - sourceStream.close(); - } - - static class DeflateStream extends InflaterInputStream { - - private boolean closed = false; - - public DeflateStream(final InputStream in, final Inflater inflater) { - super(in, inflater); - } - - @Override - public void close() throws IOException { - if (closed) { - return; - } - closed = true; - inf.end(); - super.close(); - } - - } - -} - diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/EntityBuilder.java b/lib/httpclient-android/src/main/java/org/apache/http/client/entity/EntityBuilder.java deleted file mode 100644 index a9b2098f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/EntityBuilder.java +++ /dev/null @@ -1,342 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.entity; - -import java.io.File; -import java.io.InputStream; -import java.io.Serializable; -import java.util.Arrays; -import java.util.List; - -import org.apache.http.HttpEntity; -import org.apache.http.NameValuePair; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.entity.AbstractHttpEntityHC4; -import org.apache.http.entity.BasicHttpEntityHC4; -import org.apache.http.entity.ByteArrayEntityHC4; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.FileEntityHC4; -import org.apache.http.entity.InputStreamEntityHC4; -import org.apache.http.entity.SerializableEntityHC4; -import org.apache.http.entity.StringEntityHC4; - -/** - * Builder for {@link HttpEntity} instances. - *

    - * Several setter methods of this builder are mutually exclusive. In case of multiple invocations - * of the following methods only the last one will have effect: - *

      - *
    • {@link #setText(String)}
    • - *
    • {@link #setBinary(byte[])}
    • - *
    • {@link #setStream(java.io.InputStream)}
    • - *
    • {@link #setSerializable(java.io.Serializable)}
    • - *
    • {@link #setParameters(java.util.List)}
    • - *
    • {@link #setParameters(org.apache.http.NameValuePair...)}
    • - *
    • {@link #setFile(java.io.File)}
    • - *
    - * - * @since 4.3 - */ -@NotThreadSafe -public class EntityBuilder { - - private String text; - private byte[] binary; - private InputStream stream; - private List parameters; - private Serializable serializable; - private File file; - private ContentType contentType; - private String contentEncoding; - private boolean chunked; - private boolean gzipCompress; - - EntityBuilder() { - super(); - } - - public static EntityBuilder create() { - return new EntityBuilder(); - } - - private void clearContent() { - this.text = null; - this.binary = null; - this.stream = null; - this.parameters = null; - this.serializable = null; - this.file = null; - } - - /** - * Returns entity content as a string if set using {@link #setText(String)} method. - */ - public String getText() { - return text; - } - - /** - * Sets entity content as a string. This method is mutually exclusive with - * {@link #setBinary(byte[])}, - * {@link #setStream(java.io.InputStream)} , - * {@link #setSerializable(java.io.Serializable)} , - * {@link #setParameters(java.util.List)}, - * {@link #setParameters(org.apache.http.NameValuePair...)} - * {@link #setFile(java.io.File)} methods. - */ - public EntityBuilder setText(final String text) { - clearContent(); - this.text = text; - return this; - } - - /** - * Returns entity content as a byte array if set using - * {@link #setBinary(byte[])} method. - */ - public byte[] getBinary() { - return binary; - } - - /** - * Sets entity content as a byte array. This method is mutually exclusive with - * {@link #setText(String)}, - * {@link #setStream(java.io.InputStream)} , - * {@link #setSerializable(java.io.Serializable)} , - * {@link #setParameters(java.util.List)}, - * {@link #setParameters(org.apache.http.NameValuePair...)} - * {@link #setFile(java.io.File)} methods. - */ - public EntityBuilder setBinary(final byte[] binary) { - clearContent(); - this.binary = binary; - return this; - } - - /** - * Returns entity content as a {@link InputStream} if set using - * {@link #setStream(java.io.InputStream)} method. - */ - public InputStream getStream() { - return stream; - } - - /** - * Sets entity content as a {@link InputStream}. This method is mutually exclusive with - * {@link #setText(String)}, - * {@link #setBinary(byte[])}, - * {@link #setSerializable(java.io.Serializable)} , - * {@link #setParameters(java.util.List)}, - * {@link #setParameters(org.apache.http.NameValuePair...)} - * {@link #setFile(java.io.File)} methods. - */ - public EntityBuilder setStream(final InputStream stream) { - clearContent(); - this.stream = stream; - return this; - } - - /** - * Returns entity content as a parameter list if set using - * {@link #setParameters(java.util.List)} or - * {@link #setParameters(org.apache.http.NameValuePair...)} methods. - */ - public List getParameters() { - return parameters; - } - - /** - * Sets entity content as a parameter list. This method is mutually exclusive with - * {@link #setText(String)}, - * {@link #setBinary(byte[])}, - * {@link #setStream(java.io.InputStream)} , - * {@link #setSerializable(java.io.Serializable)} , - * {@link #setFile(java.io.File)} methods. - */ - public EntityBuilder setParameters(final List parameters) { - clearContent(); - this.parameters = parameters; - return this; - } - - /** - * Sets entity content as a parameter list. This method is mutually exclusive with - * {@link #setText(String)}, - * {@link #setBinary(byte[])}, - * {@link #setStream(java.io.InputStream)} , - * {@link #setSerializable(java.io.Serializable)} , - * {@link #setFile(java.io.File)} methods. - */ - public EntityBuilder setParameters(final NameValuePair... parameters) { - return setParameters(Arrays.asList(parameters)); - } - - /** - * Returns entity content as a {@link Serializable} if set using - * {@link #setSerializable(java.io.Serializable)} method. - */ - public Serializable getSerializable() { - return serializable; - } - - /** - * Sets entity content as a {@link Serializable}. This method is mutually exclusive with - * {@link #setText(String)}, - * {@link #setBinary(byte[])}, - * {@link #setStream(java.io.InputStream)} , - * {@link #setParameters(java.util.List)}, - * {@link #setParameters(org.apache.http.NameValuePair...)} - * {@link #setFile(java.io.File)} methods. - */ - public EntityBuilder setSerializable(final Serializable serializable) { - clearContent(); - this.serializable = serializable; - return this; - } - - /** - * Returns entity content as a {@link File} if set using - * {@link #setFile(java.io.File)} method. - */ - public File getFile() { - return file; - } - - /** - * Sets entity content as a {@link File}. This method is mutually exclusive with - * {@link #setText(String)}, - * {@link #setBinary(byte[])}, - * {@link #setStream(java.io.InputStream)} , - * {@link #setParameters(java.util.List)}, - * {@link #setParameters(org.apache.http.NameValuePair...)} - * {@link #setSerializable(java.io.Serializable)} methods. - */ - public EntityBuilder setFile(final File file) { - clearContent(); - this.file = file; - return this; - } - - /** - * Returns {@link ContentType} of the entity, if set. - */ - public ContentType getContentType() { - return contentType; - } - - /** - * Sets {@link ContentType} of the entity. - */ - public EntityBuilder setContentType(final ContentType contentType) { - this.contentType = contentType; - return this; - } - - /** - * Returns content encoding of the entity, if set. - */ - public String getContentEncoding() { - return contentEncoding; - } - - /** - * Sets content encoding of the entity. - */ - public EntityBuilder setContentEncoding(final String contentEncoding) { - this.contentEncoding = contentEncoding; - return this; - } - - /** - * Returns true if entity is to be chunk coded, false otherwise. - */ - public boolean isChunked() { - return chunked; - } - - /** - * Makes entity chunk coded. - */ - public EntityBuilder chunked() { - this.chunked = true; - return this; - } - - /** - * Returns true if entity is to be GZIP compressed, false otherwise. - */ - public boolean isGzipCompress() { - return gzipCompress; - } - - /** - * Makes entity GZIP compressed. - */ - public EntityBuilder gzipCompress() { - this.gzipCompress = true; - return this; - } - - private ContentType getContentOrDefault(final ContentType def) { - return this.contentType != null ? this.contentType : def; - } - - /** - * Creates new instance of {@link HttpEntity} based on the current state. - */ - public HttpEntity build() { - final AbstractHttpEntityHC4 e; - if (this.text != null) { - e = new StringEntityHC4(this.text, getContentOrDefault(ContentType.DEFAULT_TEXT)); - } else if (this.binary != null) { - e = new ByteArrayEntityHC4(this.binary, getContentOrDefault(ContentType.DEFAULT_BINARY)); - } else if (this.stream != null) { - e = new InputStreamEntityHC4(this.stream, 1, getContentOrDefault(ContentType.DEFAULT_BINARY)); - } else if (this.parameters != null) { - e = new UrlEncodedFormEntityHC4(this.parameters, - this.contentType != null ? this.contentType.getCharset() : null); - } else if (this.serializable != null) { - e = new SerializableEntityHC4(this.serializable); - e.setContentType(ContentType.DEFAULT_BINARY.toString()); - } else if (this.file != null) { - e = new FileEntityHC4(this.file, getContentOrDefault(ContentType.DEFAULT_BINARY)); - } else { - e = new BasicHttpEntityHC4(); - } - if (e.getContentType() != null && this.contentType != null) { - e.setContentType(this.contentType.toString()); - } - e.setContentEncoding(this.contentEncoding); - e.setChunked(this.chunked); - if (this.gzipCompress) { - return new GzipCompressingEntity(e); - } - return e; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/GzipCompressingEntity.java b/lib/httpclient-android/src/main/java/org/apache/http/client/entity/GzipCompressingEntity.java deleted file mode 100644 index c98a382d..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/GzipCompressingEntity.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.entity; - -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.zip.GZIPOutputStream; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.entity.HttpEntityWrapperHC4; -import org.apache.http.message.BasicHeader; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.Args; - -/** - * Wrapping entity that compresses content when {@link #writeTo writing}. - * - * - * @since 4.0 - */ -public class GzipCompressingEntity extends HttpEntityWrapperHC4 { - - private static final String GZIP_CODEC = "gzip"; - - public GzipCompressingEntity(final HttpEntity entity) { - super(entity); - } - - @Override - public Header getContentEncoding() { - return new BasicHeader(HTTP.CONTENT_ENCODING, GZIP_CODEC); - } - - @Override - public long getContentLength() { - return -1; - } - - @Override - public boolean isChunked() { - // force content chunking - return true; - } - - @Override - public InputStream getContent() throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - final GZIPOutputStream gzip = new GZIPOutputStream(outstream); - wrappedEntity.writeTo(gzip); - // Only close output stream if the wrapped entity has been - // successfully written out - gzip.close(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/GzipDecompressingEntity.java b/lib/httpclient-android/src/main/java/org/apache/http/client/entity/GzipDecompressingEntity.java deleted file mode 100644 index 68925096..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/GzipDecompressingEntity.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.entity; - -import java.io.IOException; -import java.io.InputStream; -import java.util.zip.GZIPInputStream; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; - -/** - * {@link org.apache.http.entity.HttpEntityWrapper} for handling gzip - * Content Coded responses. - * - * @since 4.1 - */ -public class GzipDecompressingEntity extends DecompressingEntity { - - /** - * Creates a new {@link GzipDecompressingEntity} which will wrap the specified - * {@link HttpEntity}. - * - * @param entity - * the non-null {@link HttpEntity} to be wrapped - */ - public GzipDecompressingEntity(final HttpEntity entity) { - super(entity); - } - - @Override - InputStream decorate(final InputStream wrapped) throws IOException { - return new GZIPInputStream(wrapped); - } - - /** - * {@inheritDoc} - */ - @Override - public Header getContentEncoding() { - - /* This HttpEntityWrapperHC4 has dealt with the Content-Encoding. */ - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public long getContentLength() { - - /* length of ungzipped content is not known */ - return -1; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/LazyDecompressingInputStream.java b/lib/httpclient-android/src/main/java/org/apache/http/client/entity/LazyDecompressingInputStream.java deleted file mode 100644 index fb0e43b1..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/LazyDecompressingInputStream.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.entity; - -import org.apache.http.annotation.NotThreadSafe; - -import java.io.IOException; -import java.io.InputStream; - -/** - * Lazy init InputStream wrapper. - */ -@NotThreadSafe -class LazyDecompressingInputStream extends InputStream { - - private final InputStream wrappedStream; - - private final DecompressingEntity decompressingEntity; - - private InputStream wrapperStream; - - public LazyDecompressingInputStream( - final InputStream wrappedStream, - final DecompressingEntity decompressingEntity) { - this.wrappedStream = wrappedStream; - this.decompressingEntity = decompressingEntity; - } - - private void initWrapper() throws IOException { - if (wrapperStream == null) { - wrapperStream = decompressingEntity.decorate(wrappedStream); - } - } - - @Override - public int read() throws IOException { - initWrapper(); - return wrapperStream.read(); - } - - @Override - public int read(final byte[] b) throws IOException { - initWrapper(); - return wrapperStream.read(b); - } - - @Override - public int read(final byte[] b, final int off, final int len) throws IOException { - initWrapper(); - return wrapperStream.read(b, off, len); - } - - @Override - public long skip(final long n) throws IOException { - initWrapper(); - return wrapperStream.skip(n); - } - - @Override - public boolean markSupported() { - return false; - } - - @Override - public int available() throws IOException { - initWrapper(); - return wrapperStream.available(); - } - - @Override - public void close() throws IOException { - try { - if (wrapperStream != null) { - wrapperStream.close(); - } - } finally { - wrappedStream.close(); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/UrlEncodedFormEntityHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/client/entity/UrlEncodedFormEntityHC4.java deleted file mode 100644 index 44077aa6..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/UrlEncodedFormEntityHC4.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.entity; - -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.util.List; - -import org.apache.http.NameValuePair; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.client.utils.URLEncodedUtilsHC4; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntityHC4; -import org.apache.http.protocol.HTTP; - -/** - * An entity composed of a list of url-encoded pairs. - * This is typically useful while sending an HTTP POST request. - * - * @since 4.0 - */ -@NotThreadSafe // AbstractHttpEntityHC4 is not thread-safe -public class UrlEncodedFormEntityHC4 extends StringEntityHC4 { - - /** - * Constructs a new {@link UrlEncodedFormEntity} with the list - * of parameters in the specified encoding. - * - * @param parameters list of name/value pairs - * @param charset encoding the name/value pairs be encoded with - * @throws UnsupportedEncodingException if the encoding isn't supported - */ - public UrlEncodedFormEntityHC4 ( - final List parameters, - final String charset) throws UnsupportedEncodingException { - super(URLEncodedUtilsHC4.format(parameters, - charset != null ? charset : Charset.forName(HTTP.DEFAULT_CONTENT_CHARSET).name()), - ContentType.create(URLEncodedUtilsHC4.CONTENT_TYPE, charset)); - } - - /** - * Constructs a new {@link UrlEncodedFormEntity} with the list - * of parameters in the specified encoding. - * - * @param parameters iterable collection of name/value pairs - * @param charset encoding the name/value pairs be encoded with - * - * @since 4.2 - */ - public UrlEncodedFormEntityHC4 ( - final Iterable parameters, - final Charset charset) { - super(URLEncodedUtilsHC4.format(parameters, - charset != null ? charset : Charset.forName(HTTP.DEFAULT_CONTENT_CHARSET)), - ContentType.create(URLEncodedUtilsHC4.CONTENT_TYPE, charset)); - } - - /** - * Constructs a new {@link UrlEncodedFormEntity} with the list - * of parameters with the default encoding of {@link HTTP#DEFAULT_CONTENT_CHARSET} - * - * @param parameters list of name/value pairs - * @throws UnsupportedEncodingException if the default encoding isn't supported - */ - public UrlEncodedFormEntityHC4 ( - final List parameters) throws UnsupportedEncodingException { - this(parameters, (Charset) null); - } - - /** - * Constructs a new {@link UrlEncodedFormEntity} with the list - * of parameters with the default encoding of {@link HTTP#DEFAULT_CONTENT_CHARSET} - * - * @param parameters iterable collection of name/value pairs - * - * @since 4.2 - */ - public UrlEncodedFormEntityHC4 ( - final Iterable parameters) { - this(parameters, null); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/client/entity/package-info.java deleted file mode 100644 index 72390f4d..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/entity/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Client specific HTTP entity implementations. - */ -package org.apache.http.client.entity; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/AbstractExecutionAwareRequest.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/AbstractExecutionAwareRequest.java deleted file mode 100644 index 9eedf3bc..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/AbstractExecutionAwareRequest.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.methods; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import org.apache.http.HttpRequest; -import org.apache.http.client.utils.CloneUtilsHC4; -import org.apache.http.concurrent.Cancellable; -import org.apache.http.conn.ClientConnectionRequest; -import org.apache.http.conn.ConnectionReleaseTrigger; -import org.apache.http.message.AbstractHttpMessage; - -@SuppressWarnings("deprecation") -public abstract class AbstractExecutionAwareRequest extends AbstractHttpMessage implements - HttpExecutionAware, AbortableHttpRequest, Cloneable, HttpRequest { - - private final AtomicBoolean aborted; - private final AtomicReference cancellableRef; - - protected AbstractExecutionAwareRequest() { - super(); - this.aborted = new AtomicBoolean(false); - this.cancellableRef = new AtomicReference(null); - } - - @Deprecated - public void setConnectionRequest(final ClientConnectionRequest connRequest) { - setCancellable(new Cancellable() { - - public boolean cancel() { - connRequest.abortRequest(); - return true; - } - - }); - } - - @Deprecated - public void setReleaseTrigger(final ConnectionReleaseTrigger releaseTrigger) { - setCancellable(new Cancellable() { - - public boolean cancel() { - try { - releaseTrigger.abortConnection(); - return true; - } catch (final IOException ex) { - return false; - } - } - - }); - } - - public void abort() { - if (this.aborted.compareAndSet(false, true)) { - final Cancellable cancellable = this.cancellableRef.getAndSet(null); - if (cancellable != null) { - cancellable.cancel(); - } - } - } - - public boolean isAborted() { - return this.aborted.get(); - } - - /** - * @since 4.2 - */ - public void setCancellable(final Cancellable cancellable) { - if (!this.aborted.get()) { - this.cancellableRef.set(cancellable); - } - } - - @Override - public Object clone() throws CloneNotSupportedException { - final AbstractExecutionAwareRequest clone = (AbstractExecutionAwareRequest) super.clone(); - clone.headergroup = CloneUtilsHC4.cloneObject(this.headergroup); - clone.params = CloneUtilsHC4.cloneObject(this.params); - return clone; - } - - /** - * @since 4.2 - */ - public void completed() { - this.cancellableRef.set(null); - } - - /** - * Resets internal state of the request making it reusable. - * - * @since 4.2 - */ - public void reset() { - final Cancellable cancellable = this.cancellableRef.getAndSet(null); - if (cancellable != null) { - cancellable.cancel(); - } - this.aborted.set(false); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/CloseableHttpResponse.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/CloseableHttpResponse.java deleted file mode 100644 index d0391daa..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/CloseableHttpResponse.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.methods; - -import java.io.Closeable; - -import org.apache.http.HttpResponse; - -/** - * Extended version of the {@link HttpResponse} interface that also extends {@link Closeable}. - * - * @since 4.3 - */ -public interface CloseableHttpResponse extends HttpResponse, Closeable { -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/Configurable.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/Configurable.java deleted file mode 100644 index 42f098ec..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/Configurable.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.methods; - -import org.apache.http.client.config.RequestConfig; - -/** - * Configuration interface for HTTP requests. - * - * @since 4.3 - */ -public interface Configurable { - - /** - * Returns actual request configuration. - */ - RequestConfig getConfig(); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpDeleteHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpDeleteHC4.java deleted file mode 100644 index 9a5fae15..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpDeleteHC4.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.methods; - -import java.net.URI; - -import org.apache.http.annotation.NotThreadSafe; - -/** - * HTTP DELETE method - *

    - * The HTTP DELETE method is defined in section 9.7 of - * RFC2616: - *

    - * The DELETE method requests that the origin server delete the resource - * identified by the Request-URI. [...] The client cannot - * be guaranteed that the operation has been carried out, even if the - * status code returned from the origin server indicates that the action - * has been completed successfully. - *
    - * - * @since 4.0 - */ -@NotThreadSafe // HttpRequestBaseHC4 is @NotThreadSafe -public class HttpDeleteHC4 extends HttpRequestBaseHC4 { - - public final static String METHOD_NAME = "DELETE"; - - - public HttpDeleteHC4() { - super(); - } - - public HttpDeleteHC4(final URI uri) { - super(); - setURI(uri); - } - - /** - * @throws IllegalArgumentException if the uri is invalid. - */ - public HttpDeleteHC4(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpEntityEnclosingRequestBaseHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpEntityEnclosingRequestBaseHC4.java deleted file mode 100644 index 299b9e1b..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpEntityEnclosingRequestBaseHC4.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.methods; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.client.utils.CloneUtilsHC4; -import org.apache.http.protocol.HTTP; - -/** - * Basic implementation of an entity enclosing HTTP request - * that can be modified - * - * @since 4.0 - */ -@NotThreadSafe // HttpRequestBaseHC4 is @NotThreadSafe -public abstract class HttpEntityEnclosingRequestBaseHC4 - extends HttpRequestBaseHC4 implements HttpEntityEnclosingRequest { - - private HttpEntity entity; - - public HttpEntityEnclosingRequestBaseHC4() { - super(); - } - - public HttpEntity getEntity() { - return this.entity; - } - - public void setEntity(final HttpEntity entity) { - this.entity = entity; - } - - public boolean expectContinue() { - final Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE); - return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue()); - } - - @Override - public Object clone() throws CloneNotSupportedException { - final HttpEntityEnclosingRequestBaseHC4 clone = - (HttpEntityEnclosingRequestBaseHC4) super.clone(); - if (this.entity != null) { - clone.entity = CloneUtilsHC4.cloneObject(this.entity); - } - return clone; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpExecutionAware.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpExecutionAware.java deleted file mode 100644 index 0a52376b..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpExecutionAware.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.methods; - -import org.apache.http.concurrent.Cancellable; - -/** - * Interface to be implemented by any object that wishes to be notified of - * blocking I/O operations that could be cancelled. - * - * @since 4.3 - */ -public interface HttpExecutionAware { - - boolean isAborted(); - - /** - * Sets {@link Cancellable} for the ongoing operation. - */ - void setCancellable(Cancellable cancellable); - -} - diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpGetHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpGetHC4.java deleted file mode 100644 index e4fa5c9f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpGetHC4.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.methods; - -import java.net.URI; - -import org.apache.http.annotation.NotThreadSafe; - -/** - * HTTP GET method. - *

    - * The HTTP GET method is defined in section 9.3 of - * RFC2616: - *

    - * The GET method means retrieve whatever information (in the form of an - * entity) is identified by the Request-URI. If the Request-URI refers - * to a data-producing process, it is the produced data which shall be - * returned as the entity in the response and not the source text of the - * process, unless that text happens to be the output of the process. - *
    - *

    - * - * @since 4.0 - */ -@NotThreadSafe -public class HttpGetHC4 extends HttpRequestBaseHC4 { - - public final static String METHOD_NAME = "GET"; - - public HttpGetHC4() { - super(); - } - - public HttpGetHC4(final URI uri) { - super(); - setURI(uri); - } - - /** - * @throws IllegalArgumentException if the uri is invalid. - */ - public HttpGetHC4(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpHeadHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpHeadHC4.java deleted file mode 100644 index d596d9bb..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpHeadHC4.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.methods; - -import java.net.URI; - -import org.apache.http.annotation.NotThreadSafe; - -/** - * HTTP HEAD method. - *

    - * The HTTP HEAD method is defined in section 9.4 of - * RFC2616: - *

    - * The HEAD method is identical to GET except that the server MUST NOT - * return a message-body in the response. The metainformation contained - * in the HTTP headers in response to a HEAD request SHOULD be identical - * to the information sent in response to a GET request. This method can - * be used for obtaining metainformation about the entity implied by the - * request without transferring the entity-body itself. This method is - * often used for testing hypertext links for validity, accessibility, - * and recent modification. - *
    - *

    - * - * @since 4.0 - */ -@NotThreadSafe -public class HttpHeadHC4 extends HttpRequestBaseHC4 { - - public final static String METHOD_NAME = "HEAD"; - - public HttpHeadHC4() { - super(); - } - - public HttpHeadHC4(final URI uri) { - super(); - setURI(uri); - } - - /** - * @throws IllegalArgumentException if the uri is invalid. - */ - public HttpHeadHC4(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpOptionsHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpOptionsHC4.java deleted file mode 100644 index 9e045635..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpOptionsHC4.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.methods; - -import java.net.URI; -import java.util.HashSet; -import java.util.Set; - -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.HeaderIterator; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.util.Args; - -/** - * HTTP OPTIONS method. - *

    - * The HTTP OPTIONS method is defined in section 9.2 of - * RFC2616: - *

    - * The OPTIONS method represents a request for information about the - * communication options available on the request/response chain - * identified by the Request-URI. This method allows the client to - * determine the options and/or requirements associated with a resource, - * or the capabilities of a server, without implying a resource action - * or initiating a resource retrieval. - *
    - *

    - * - * @since 4.0 - */ -@NotThreadSafe -public class HttpOptionsHC4 extends HttpRequestBaseHC4 { - - public final static String METHOD_NAME = "OPTIONS"; - - public HttpOptionsHC4() { - super(); - } - - public HttpOptionsHC4(final URI uri) { - super(); - setURI(uri); - } - - /** - * @throws IllegalArgumentException if the uri is invalid. - */ - public HttpOptionsHC4(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; - } - - public Set getAllowedMethods(final HttpResponse response) { - Args.notNull(response, "HTTP response"); - - final HeaderIterator it = response.headerIterator("Allow"); - final Set methods = new HashSet(); - while (it.hasNext()) { - final Header header = it.nextHeader(); - final HeaderElement[] elements = header.getElements(); - for (final HeaderElement element : elements) { - methods.add(element.getName()); - } - } - return methods; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpPatch.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpPatch.java deleted file mode 100644 index fa7ffb69..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpPatch.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.methods; - -import java.net.URI; - -import org.apache.http.annotation.NotThreadSafe; - -/** - * HTTP PATCH method. - *

    - * The HTTP PATCH method is defined in RF5789:

    The PATCH - * method requests that a set of changes described in the request entity be - * applied to the resource identified by the Request- URI. Differs from the PUT - * method in the way the server processes the enclosed entity to modify the - * resource identified by the Request-URI. In a PUT request, the enclosed entity - * origin server, and the client is requesting that the stored version be - * replaced. With PATCH, however, the enclosed entity contains a set of - * instructions describing how a resource currently residing on the origin - * server should be modified to produce a new version.
    - *

    - * - * @since 4.2 - */ -@NotThreadSafe -public class HttpPatch extends HttpEntityEnclosingRequestBaseHC4 { - - public final static String METHOD_NAME = "PATCH"; - - public HttpPatch() { - super(); - } - - public HttpPatch(final URI uri) { - super(); - setURI(uri); - } - - public HttpPatch(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpPostHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpPostHC4.java deleted file mode 100644 index 08116c6d..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpPostHC4.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.methods; - -import java.net.URI; - -import org.apache.http.annotation.NotThreadSafe; - -/** - * HTTP POST method. - *

    - * The HTTP POST method is defined in section 9.5 of - * RFC2616: - *

    - * The POST method is used to request that the origin server accept the entity - * enclosed in the request as a new subordinate of the resource identified by - * the Request-URI in the Request-Line. POST is designed to allow a uniform - * method to cover the following functions: - *
      - *
    • Annotation of existing resources
    • - *
    • Posting a message to a bulletin board, newsgroup, mailing list, or - * similar group of articles
    • - *
    • Providing a block of data, such as the result of submitting a form, - * to a data-handling process
    • - *
    • Extending a database through an append operation
    • - *
    - *
    - *

    - * - * @since 4.0 - */ -@NotThreadSafe -public class HttpPostHC4 extends HttpEntityEnclosingRequestBaseHC4 { - - public final static String METHOD_NAME = "POST"; - - public HttpPostHC4() { - super(); - } - - public HttpPostHC4(final URI uri) { - super(); - setURI(uri); - } - - /** - * @throws IllegalArgumentException if the uri is invalid. - */ - public HttpPostHC4(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpPutHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpPutHC4.java deleted file mode 100644 index cadc0b98..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpPutHC4.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.methods; - -import java.net.URI; - -import org.apache.http.annotation.NotThreadSafe; - -/** - * HTTP PUT method. - *

    - * The HTTP PUT method is defined in section 9.6 of - * RFC2616: - *

    - * The PUT method requests that the enclosed entity be stored under the - * supplied Request-URI. If the Request-URI refers to an already - * existing resource, the enclosed entity SHOULD be considered as a - * modified version of the one residing on the origin server. - *
    - *

    - * - * @since 4.0 - */ -@NotThreadSafe -public class HttpPutHC4 extends HttpEntityEnclosingRequestBaseHC4 { - - public final static String METHOD_NAME = "PUT"; - - public HttpPutHC4() { - super(); - } - - public HttpPutHC4(final URI uri) { - super(); - setURI(uri); - } - - /** - * @throws IllegalArgumentException if the uri is invalid. - */ - public HttpPutHC4(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpRequestBaseHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpRequestBaseHC4.java deleted file mode 100644 index 2c9f3bd4..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpRequestBaseHC4.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.methods; - -import java.net.URI; - -import org.apache.http.ProtocolVersion; -import org.apache.http.RequestLine; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.message.BasicRequestLine; -import org.apache.http.params.HttpProtocolParams; - -/** - * Base implementation of {@link HttpUriRequest}. - * - * @since 4.0 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe -public abstract class HttpRequestBaseHC4 extends AbstractExecutionAwareRequest - implements HttpUriRequest, Configurable { - - private ProtocolVersion version; - private URI uri; - private RequestConfig config; - - public abstract String getMethod(); - - /** - * @since 4.3 - */ - public void setProtocolVersion(final ProtocolVersion version) { - this.version = version; - } - - public ProtocolVersion getProtocolVersion() { - return version != null ? version : HttpProtocolParams.getVersion(getParams()); - } - - /** - * Returns the original request URI. - *

    - * Please note URI remains unchanged in the course of request execution and - * is not updated if the request is redirected to another location. - */ - public URI getURI() { - return this.uri; - } - - public RequestLine getRequestLine() { - final String method = getMethod(); - final ProtocolVersion ver = getProtocolVersion(); - final URI uri = getURI(); - String uritext = null; - if (uri != null) { - uritext = uri.toASCIIString(); - } - if (uritext == null || uritext.length() == 0) { - uritext = "/"; - } - return new BasicRequestLine(method, uritext, ver); - } - - - public RequestConfig getConfig() { - return config; - } - - public void setConfig(final RequestConfig config) { - this.config = config; - } - - public void setURI(final URI uri) { - this.uri = uri; - } - - /** - * @since 4.2 - */ - public void started() { - } - - /** - * A convenience method to simplify migration from HttpClient 3.1 API. This method is - * equivalent to {@link #reset()}. - * - * @since 4.2 - */ - public void releaseConnection() { - reset(); - } - - @Override - public String toString() { - return getMethod() + " " + getURI() + " " + getProtocolVersion(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpRequestWrapper.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpRequestWrapper.java deleted file mode 100644 index 771185f5..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpRequestWrapper.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.methods; - -import java.net.URI; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpRequest; -import org.apache.http.ProtocolVersion; -import org.apache.http.RequestLine; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.message.AbstractHttpMessage; -import org.apache.http.message.BasicRequestLine; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HTTP; - -/** - * A wrapper class for {@link HttpRequest} that can be used to change properties of the current - * request without modifying the original object. - * - * @since 4.3 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe -public class HttpRequestWrapper extends AbstractHttpMessage implements HttpUriRequest { - - private final HttpRequest original; - private final String method; - private ProtocolVersion version; - private URI uri; - - private HttpRequestWrapper(final HttpRequest request) { - super(); - this.original = request; - this.version = this.original.getRequestLine().getProtocolVersion(); - this.method = this.original.getRequestLine().getMethod(); - if (request instanceof HttpUriRequest) { - this.uri = ((HttpUriRequest) request).getURI(); - } else { - this.uri = null; - } - setHeaders(request.getAllHeaders()); - } - - public ProtocolVersion getProtocolVersion() { - return this.version != null ? this.version : this.original.getProtocolVersion(); - } - - public void setProtocolVersion(final ProtocolVersion version) { - this.version = version; - } - - public URI getURI() { - return this.uri; - } - - public void setURI(final URI uri) { - this.uri = uri; - } - - public String getMethod() { - return method; - } - - public void abort() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - public boolean isAborted() { - return false; - } - - public RequestLine getRequestLine() { - String requestUri = null; - if (this.uri != null) { - requestUri = this.uri.toASCIIString(); - } else { - requestUri = this.original.getRequestLine().getUri(); - } - if (requestUri == null || requestUri.length() == 0) { - requestUri = "/"; - } - return new BasicRequestLine(this.method, requestUri, getProtocolVersion()); - } - - public HttpRequest getOriginal() { - return this.original; - } - - @Override - public String toString() { - return getRequestLine() + " " + this.headergroup; - } - - static class HttpEntityEnclosingRequestWrapper extends HttpRequestWrapper - implements HttpEntityEnclosingRequest { - - private HttpEntity entity; - - public HttpEntityEnclosingRequestWrapper(final HttpEntityEnclosingRequest request) { - super(request); - this.entity = request.getEntity(); - } - - public HttpEntity getEntity() { - return this.entity; - } - - public void setEntity(final HttpEntity entity) { - this.entity = entity; - } - - public boolean expectContinue() { - final Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE); - return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue()); - } - - } - - public static HttpRequestWrapper wrap(final HttpRequest request) { - if (request == null) { - return null; - } - if (request instanceof HttpEntityEnclosingRequest) { - return new HttpEntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request); - } else { - return new HttpRequestWrapper(request); - } - } - - /** - * @deprecated (4.3) use - * {@link org.apache.http.client.config.RequestConfig}. - */ - @Override - @Deprecated - public HttpParams getParams() { - if (this.params == null) { - this.params = original.getParams().copy(); - } - return this.params; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpTraceHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpTraceHC4.java deleted file mode 100644 index 687549c6..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/HttpTraceHC4.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.methods; - -import java.net.URI; - -import org.apache.http.annotation.NotThreadSafe; - -/** - * HTTP TRACE method. - *

    - * The HTTP TRACE method is defined in section 9.6 of - * RFC2616: - *

    - * The TRACE method is used to invoke a remote, application-layer loop- - * back of the request message. The final recipient of the request - * SHOULD reflect the message received back to the client as the - * entity-body of a 200 (OK) response. The final recipient is either the - * origin server or the first proxy or gateway to receive a Max-Forwards - * value of zero (0) in the request (see section 14.31). A TRACE request - * MUST NOT include an entity. - *
    - *

    - * - * @since 4.0 - */ -@NotThreadSafe -public class HttpTraceHC4 extends HttpRequestBaseHC4 { - - public final static String METHOD_NAME = "TRACE"; - - public HttpTraceHC4() { - super(); - } - - public HttpTraceHC4(final URI uri) { - super(); - setURI(uri); - } - - /** - * @throws IllegalArgumentException if the uri is invalid. - */ - public HttpTraceHC4(final String uri) { - super(); - setURI(URI.create(uri)); - } - - @Override - public String getMethod() { - return METHOD_NAME; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/RequestBuilder.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/RequestBuilder.java deleted file mode 100644 index 6de352a4..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/RequestBuilder.java +++ /dev/null @@ -1,352 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.methods; - -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -import org.apache.http.Header; -import org.apache.http.HeaderIterator; -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpRequest; -import org.apache.http.NameValuePair; -import org.apache.http.ProtocolVersion; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.entity.UrlEncodedFormEntityHC4; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.message.BasicHeader; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.message.HeaderGroup; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.Args; - -/** - * Builder for {@link HttpUriRequest} instances. - *

    - * Please note that this class treats parameters differently depending on composition - * of the request: if the request has a content entity explicitly set with - * {@link #setEntity(org.apache.http.HttpEntity)} or it is not an entity enclosing method - * (such as POST or PUT), parameters will be added to the query component of the request URI. - * Otherwise, parameters will be added as a URL encoded {@link UrlEncodedFormEntityHC4 entity}. - * - * @since 4.3 - */ -@NotThreadSafe -public class RequestBuilder { - - private String method; - private ProtocolVersion version; - private URI uri; - private HeaderGroup headergroup; - private HttpEntity entity; - private LinkedList parameters; - private RequestConfig config; - - RequestBuilder(final String method) { - super(); - this.method = method; - } - - RequestBuilder() { - this(null); - } - - public static RequestBuilder create(final String method) { - Args.notBlank(method, "HTTP method"); - return new RequestBuilder(method); - } - - public static RequestBuilder get() { - return new RequestBuilder(HttpGetHC4.METHOD_NAME); - } - - public static RequestBuilder head() { - return new RequestBuilder(HttpHeadHC4.METHOD_NAME); - } - - public static RequestBuilder post() { - return new RequestBuilder(HttpPostHC4.METHOD_NAME); - } - - public static RequestBuilder put() { - return new RequestBuilder(HttpPutHC4.METHOD_NAME); - } - - public static RequestBuilder delete() { - return new RequestBuilder(HttpDeleteHC4.METHOD_NAME); - } - - public static RequestBuilder trace() { - return new RequestBuilder(HttpTraceHC4.METHOD_NAME); - } - - public static RequestBuilder options() { - return new RequestBuilder(HttpOptionsHC4.METHOD_NAME); - } - - public static RequestBuilder copy(final HttpRequest request) { - Args.notNull(request, "HTTP request"); - return new RequestBuilder().doCopy(request); - } - - private RequestBuilder doCopy(final HttpRequest request) { - if (request == null) { - return this; - } - method = request.getRequestLine().getMethod(); - version = request.getRequestLine().getProtocolVersion(); - if (request instanceof HttpUriRequest) { - uri = ((HttpUriRequest) request).getURI(); - } else { - uri = URI.create(request.getRequestLine().getUri()); - } - if (headergroup == null) { - headergroup = new HeaderGroup(); - } - headergroup.clear(); - headergroup.setHeaders(request.getAllHeaders()); - if (request instanceof HttpEntityEnclosingRequest) { - entity = ((HttpEntityEnclosingRequest) request).getEntity(); - } else { - entity = null; - } - if (request instanceof Configurable) { - this.config = ((Configurable) request).getConfig(); - } else { - this.config = null; - } - this.parameters = null; - return this; - } - - public String getMethod() { - return method; - } - - public ProtocolVersion getVersion() { - return version; - } - - public RequestBuilder setVersion(final ProtocolVersion version) { - this.version = version; - return this; - } - - public URI getUri() { - return uri; - } - - public RequestBuilder setUri(final URI uri) { - this.uri = uri; - return this; - } - - public RequestBuilder setUri(final String uri) { - this.uri = uri != null ? URI.create(uri) : null; - return this; - } - - public Header getFirstHeader(final String name) { - return headergroup != null ? headergroup.getFirstHeader(name) : null; - } - - public Header getLastHeader(final String name) { - return headergroup != null ? headergroup.getLastHeader(name) : null; - } - - public Header[] getHeaders(final String name) { - return headergroup != null ? headergroup.getHeaders(name) : null; - } - - public RequestBuilder addHeader(final Header header) { - if (headergroup == null) { - headergroup = new HeaderGroup(); - } - headergroup.addHeader(header); - return this; - } - - public RequestBuilder addHeader(final String name, final String value) { - if (headergroup == null) { - headergroup = new HeaderGroup(); - } - this.headergroup.addHeader(new BasicHeader(name, value)); - return this; - } - - public RequestBuilder removeHeader(final Header header) { - if (headergroup == null) { - headergroup = new HeaderGroup(); - } - headergroup.removeHeader(header); - return this; - } - - public RequestBuilder removeHeaders(final String name) { - if (name == null || headergroup == null) { - return this; - } - for (final HeaderIterator i = headergroup.iterator(); i.hasNext(); ) { - final Header header = i.nextHeader(); - if (name.equalsIgnoreCase(header.getName())) { - i.remove(); - } - } - return this; - } - - public RequestBuilder setHeader(final Header header) { - if (headergroup == null) { - headergroup = new HeaderGroup(); - } - this.headergroup.updateHeader(header); - return this; - } - - public RequestBuilder setHeader(final String name, final String value) { - if (headergroup == null) { - headergroup = new HeaderGroup(); - } - this.headergroup.updateHeader(new BasicHeader(name, value)); - return this; - } - - public HttpEntity getEntity() { - return entity; - } - - public RequestBuilder setEntity(final HttpEntity entity) { - this.entity = entity; - return this; - } - - public List getParameters() { - return parameters != null ? new ArrayList(parameters) : - new ArrayList(); - } - - public RequestBuilder addParameter(final NameValuePair nvp) { - Args.notNull(nvp, "Name value pair"); - if (parameters == null) { - parameters = new LinkedList(); - } - parameters.add(nvp); - return this; - } - - public RequestBuilder addParameter(final String name, final String value) { - return addParameter(new BasicNameValuePair(name, value)); - } - - public RequestBuilder addParameters(final NameValuePair... nvps) { - for (final NameValuePair nvp: nvps) { - addParameter(nvp); - } - return this; - } - - public RequestConfig getConfig() { - return config; - } - - public RequestBuilder setConfig(final RequestConfig config) { - this.config = config; - return this; - } - - public HttpUriRequest build() { - final HttpRequestBaseHC4 result; - URI uri = this.uri != null ? this.uri : URI.create("/"); - HttpEntity entity = this.entity; - if (parameters != null && !parameters.isEmpty()) { - if (entity == null && (HttpPostHC4.METHOD_NAME.equalsIgnoreCase(method) - || HttpPutHC4.METHOD_NAME.equalsIgnoreCase(method))) { - entity = new UrlEncodedFormEntityHC4(parameters, Charset.forName(HTTP.DEFAULT_CONTENT_CHARSET)); - } else { - try { - uri = new URIBuilder(uri).addParameters(parameters).build(); - } catch (final URISyntaxException ex) { - // should never happen - } - } - } - if (entity == null) { - result = new InternalRequest(method); - } else { - final InternalEntityEclosingRequest request = new InternalEntityEclosingRequest(method); - request.setEntity(entity); - result = request; - } - result.setProtocolVersion(this.version); - result.setURI(uri); - if (this.headergroup != null) { - result.setHeaders(this.headergroup.getAllHeaders()); - } - result.setConfig(this.config); - return result; - } - - static class InternalRequest extends HttpRequestBaseHC4 { - - private final String method; - - InternalRequest(final String method) { - super(); - this.method = method; - } - - @Override - public String getMethod() { - return this.method; - } - - } - - static class InternalEntityEclosingRequest extends HttpEntityEnclosingRequestBaseHC4 { - - private final String method; - - InternalEntityEclosingRequest(final String method) { - super(); - this.method = method; - } - - @Override - public String getMethod() { - return this.method; - } - - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/client/methods/package-info.java deleted file mode 100644 index 20fa1723..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/methods/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Standard HTTP method implementations. - */ -package org.apache.http.client.methods; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/client/package-info.java deleted file mode 100644 index 3b181d71..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Client HTTP communication APIs. - */ -package org.apache.http.client; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/params/HttpClientParamConfig.java b/lib/httpclient-android/src/main/java/org/apache/http/client/params/HttpClientParamConfig.java deleted file mode 100644 index 5b93015a..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/params/HttpClientParamConfig.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.params; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.net.InetAddress; -import java.util.Map; - -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.conn.params.ConnRoutePNames; -import org.apache.http.params.CoreConnectionPNames; -import org.apache.http.params.CoreProtocolPNames; -import org.apache.http.params.HttpParams; - -/** - * @deprecated (4.3) provided for compatibility with {@link HttpParams}. Do not use. - * - * @since 4.3 - */ -@Deprecated -public final class HttpClientParamConfig { - - private HttpClientParamConfig() { - } - - @SuppressWarnings("unchecked") - public static RequestConfig getRequestConfig(final HttpParams params) { - if (params == null) { - return null; - } - try { - final Field f = params.getClass().getDeclaredField("parameters"); - f.setAccessible(true); - final Map map = (Map) f.get(params); - if (map == null || map.isEmpty()) { - return null; - } - } catch (Exception ignore) { - } - return RequestConfig.custom() - .setSocketTimeout(params.getIntParameter( - CoreConnectionPNames.SO_TIMEOUT, 0)) - .setStaleConnectionCheckEnabled(params.getBooleanParameter( - CoreConnectionPNames.STALE_CONNECTION_CHECK, true)) - .setConnectTimeout(params.getIntParameter( - CoreConnectionPNames.CONNECTION_TIMEOUT, 0)) - .setExpectContinueEnabled(params.getBooleanParameter( - CoreProtocolPNames.USE_EXPECT_CONTINUE, false)) - .setProxy((HttpHost) params.getParameter( - ConnRoutePNames.DEFAULT_PROXY)) - .setLocalAddress((InetAddress) params.getParameter( - ConnRoutePNames.LOCAL_ADDRESS)) - .setAuthenticationEnabled(params.getBooleanParameter( - ClientPNames.HANDLE_AUTHENTICATION, true)) - .setCircularRedirectsAllowed(params.getBooleanParameter( - ClientPNames.ALLOW_CIRCULAR_REDIRECTS, false)) - .setCookieSpec((String) params.getParameter( - ClientPNames.COOKIE_POLICY)) - .setMaxRedirects(params.getIntParameter( - ClientPNames.MAX_REDIRECTS, 50)) - .setRedirectsEnabled(params.getBooleanParameter( - ClientPNames.HANDLE_REDIRECTS, true)) - .setRelativeRedirectsAllowed(!params.getBooleanParameter( - ClientPNames.REJECT_RELATIVE_REDIRECT, false)) - .build(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/params/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/client/params/package-info.java deleted file mode 100644 index 69fb42a8..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/params/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Deprecated. - * @deprecated (4.3). - */ -package org.apache.http.client.params; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/HttpClientContext.java b/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/HttpClientContext.java deleted file mode 100644 index fa9396d9..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/HttpClientContext.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.protocol; - -import java.net.URI; -import java.util.List; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.auth.AuthSchemeProvider; -import org.apache.http.auth.AuthStateHC4; -import org.apache.http.client.AuthCache; -import org.apache.http.client.CookieStore; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.config.Lookup; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.conn.routing.RouteInfo; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.CookieSpec; -import org.apache.http.cookie.CookieSpecProvider; -import org.apache.http.protocol.BasicHttpContextHC4; -import org.apache.http.protocol.HttpContext; -import org.apache.http.protocol.HttpCoreContext; - -/** - * Adaptor class that provides convenience type safe setters and getters - * for common {@link HttpContext} attributes used in the course - * of HTTP request execution. - * - * @since 4.3 - */ -@NotThreadSafe -public class HttpClientContext extends HttpCoreContext { - - /** - * Attribute name of a {@link org.apache.http.conn.routing.RouteInfo} - * object that represents the actual connection route. - */ - public static final String HTTP_ROUTE = "http.route"; - - /** - * Attribute name of a {@link List} object that represents a collection of all - * redirect locations received in the process of request execution. - */ - public static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations"; - - /** - * Attribute name of a {@link org.apache.http.config.Lookup} object that represents - * the actual {@link CookieSpecProvider} registry. - */ - public static final String COOKIESPEC_REGISTRY = "http.cookiespec-registry"; - - /** - * Attribute name of a {@link org.apache.http.cookie.CookieSpec} - * object that represents the actual cookie specification. - */ - public static final String COOKIE_SPEC = "http.cookie-spec"; - - /** - * Attribute name of a {@link org.apache.http.cookie.CookieOrigin} - * object that represents the actual details of the origin server. - */ - public static final String COOKIE_ORIGIN = "http.cookie-origin"; - - /** - * Attribute name of a {@link org.apache.http.client.CookieStore} - * object that represents the actual cookie store. - */ - public static final String COOKIE_STORE = "http.cookie-store"; - - /** - * Attribute name of a {@link org.apache.http.client.CredentialsProvider} - * object that represents the actual credentials provider. - */ - public static final String CREDS_PROVIDER = "http.auth.credentials-provider"; - - /** - * Attribute name of a {@link org.apache.http.client.AuthCache} object - * that represents the auth scheme cache. - */ - public static final String AUTH_CACHE = "http.auth.auth-cache"; - - /** - * Attribute name of a {@link org.apache.http.auth.AuthState} - * object that represents the actual target authentication state. - */ - public static final String TARGET_AUTH_STATE = "http.auth.target-scope"; - - /** - * Attribute name of a {@link org.apache.http.auth.AuthState} - * object that represents the actual proxy authentication state. - */ - public static final String PROXY_AUTH_STATE = "http.auth.proxy-scope"; - - /** - * Attribute name of a {@link java.lang.Object} object that represents - * the actual user identity such as user {@link java.security.Principal}. - */ - public static final String USER_TOKEN = "http.user-token"; - - /** - * Attribute name of a {@link org.apache.http.config.Lookup} object that represents - * the actual {@link AuthSchemeProvider} registry. - */ - public static final String AUTHSCHEME_REGISTRY = "http.authscheme-registry"; - - /** - * Attribute name of a {@link org.apache.http.client.config.RequestConfig} object that - * represents the actual request configuration. - */ - public static final String REQUEST_CONFIG = "http.request-config"; - - public static HttpClientContext adapt(final HttpContext context) { - if (context instanceof HttpClientContext) { - return (HttpClientContext) context; - } else { - return new HttpClientContext(context); - } - } - - public static HttpClientContext create() { - return new HttpClientContext(new BasicHttpContextHC4()); - } - - public HttpClientContext(final HttpContext context) { - super(context); - } - - public HttpClientContext() { - super(); - } - - public RouteInfo getHttpRoute() { - return getAttribute(HTTP_ROUTE, HttpRoute.class); - } - - @SuppressWarnings("unchecked") - public List getRedirectLocations() { - return getAttribute(REDIRECT_LOCATIONS, List.class); - } - - public CookieStore getCookieStore() { - return getAttribute(COOKIE_STORE, CookieStore.class); - } - - public void setCookieStore(final CookieStore cookieStore) { - setAttribute(COOKIE_STORE, cookieStore); - } - - public CookieSpec getCookieSpec() { - return getAttribute(COOKIE_SPEC, CookieSpec.class); - } - - public CookieOrigin getCookieOrigin() { - return getAttribute(COOKIE_ORIGIN, CookieOrigin.class); - } - - @SuppressWarnings("unchecked") - private Lookup getLookup(final String name, final Class clazz) { - return getAttribute(name, Lookup.class); - } - - public Lookup getCookieSpecRegistry() { - return getLookup(COOKIESPEC_REGISTRY, CookieSpecProvider.class); - } - - public void setCookieSpecRegistry(final Lookup lookup) { - setAttribute(COOKIESPEC_REGISTRY, lookup); - } - - public Lookup getAuthSchemeRegistry() { - return getLookup(AUTHSCHEME_REGISTRY, AuthSchemeProvider.class); - } - - public void setAuthSchemeRegistry(final Lookup lookup) { - setAttribute(AUTHSCHEME_REGISTRY, lookup); - } - - public CredentialsProvider getCredentialsProvider() { - return getAttribute(CREDS_PROVIDER, CredentialsProvider.class); - } - - public void setCredentialsProvider(final CredentialsProvider credentialsProvider) { - setAttribute(CREDS_PROVIDER, credentialsProvider); - } - - public AuthCache getAuthCache() { - return getAttribute(AUTH_CACHE, AuthCache.class); - } - - public void setAuthCache(final AuthCache authCache) { - setAttribute(AUTH_CACHE, authCache); - } - - public AuthStateHC4 getTargetAuthState() { - return getAttribute(TARGET_AUTH_STATE, AuthStateHC4.class); - } - - public AuthStateHC4 getProxyAuthState() { - return getAttribute(PROXY_AUTH_STATE, AuthStateHC4.class); - } - - public T getUserToken(final Class clazz) { - return getAttribute(USER_TOKEN, clazz); - } - - public Object getUserToken() { - return getAttribute(USER_TOKEN); - } - - public void setUserToken(final Object obj) { - setAttribute(USER_TOKEN, obj); - } - - public RequestConfig getRequestConfig() { - final RequestConfig config = getAttribute(REQUEST_CONFIG, RequestConfig.class); - return config != null ? config : RequestConfig.DEFAULT; - } - - public void setRequestConfig(final RequestConfig config) { - setAttribute(REQUEST_CONFIG, config); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestAcceptEncoding.java b/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestAcceptEncoding.java deleted file mode 100644 index 610c7459..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestAcceptEncoding.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.protocol; - -import java.io.IOException; - -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.annotation.Immutable; -import org.apache.http.protocol.HttpContext; - -/** - * Class responsible for handling Content Encoding requests in HTTP. - *

    - * Instances of this class are stateless, therefore they're thread-safe and immutable. - * - * @see "http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5" - * - * @since 4.1 - */ -@Immutable -public class RequestAcceptEncoding implements HttpRequestInterceptor { - - /** - * Adds the header {@code "Accept-Encoding: gzip,deflate"} to the request. - */ - public void process( - final HttpRequest request, - final HttpContext context) throws HttpException, IOException { - - /* Signal support for Accept-Encoding transfer encodings. */ - if (!request.containsHeader("Accept-Encoding")) { - request.addHeader("Accept-Encoding", "gzip,deflate"); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestAddCookiesHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestAddCookiesHC4.java deleted file mode 100644 index c6bee3de..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestAddCookiesHC4.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.protocol; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import android.util.Log; - -import org.apache.http.Header; -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.annotation.Immutable; -import org.apache.http.client.CookieStore; -import org.apache.http.client.config.CookieSpecs; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.config.Lookup; -import org.apache.http.conn.routing.RouteInfo; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.CookieSpec; -import org.apache.http.cookie.CookieSpecProvider; -import org.apache.http.cookie.SetCookie2; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; -import org.apache.http.util.TextUtils; - -/** - * Request interceptor that matches cookies available in the current - * {@link CookieStore} to the request being executed and generates - * corresponding Cookie request headers. - * - * @since 4.0 - */ -@Immutable -public class RequestAddCookiesHC4 implements HttpRequestInterceptor { - - private final static String TAG = "HttpClient"; - - public RequestAddCookiesHC4() { - super(); - } - - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - Args.notNull(context, "HTTP context"); - - final String method = request.getRequestLine().getMethod(); - if (method.equalsIgnoreCase("CONNECT")) { - return; - } - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - // Obtain cookie store - final CookieStore cookieStore = clientContext.getCookieStore(); - if (cookieStore == null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Cookie store not specified in HTTP context"); - } - return; - } - - // Obtain the registry of cookie specs - final Lookup registry = clientContext.getCookieSpecRegistry(); - if (registry == null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "CookieSpec registry not specified in HTTP context"); - } - return; - } - - // Obtain the target host, possibly virtual (required) - final HttpHost targetHost = clientContext.getTargetHost(); - if (targetHost == null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Target host not set in the context"); - } - return; - } - - // Obtain the route (required) - final RouteInfo route = clientContext.getHttpRoute(); - if (route == null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Connection route not set in the context"); - } - return; - } - - final RequestConfig config = clientContext.getRequestConfig(); - String policy = config.getCookieSpec(); - if (policy == null) { - policy = CookieSpecs.BEST_MATCH; - } - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "CookieSpec selected: " + policy); - } - - URI requestURI = null; - if (request instanceof HttpUriRequest) { - requestURI = ((HttpUriRequest) request).getURI(); - } else { - try { - requestURI = new URI(request.getRequestLine().getUri()); - } catch (final URISyntaxException ignore) { - } - } - final String path = requestURI != null ? requestURI.getPath() : null; - final String hostName = targetHost.getHostName(); - int port = targetHost.getPort(); - if (port < 0) { - port = route.getTargetHost().getPort(); - } - - final CookieOrigin cookieOrigin = new CookieOrigin( - hostName, - port >= 0 ? port : 0, - !TextUtils.isEmpty(path) ? path : "/", - route.isSecure()); - - // Get an instance of the selected cookie policy - final CookieSpecProvider provider = registry.lookup(policy); - if (provider == null) { - throw new HttpException("Unsupported cookie policy: " + policy); - } - final CookieSpec cookieSpec = provider.create(clientContext); - // Get all cookies available in the HTTP state - final List cookies = new ArrayList(cookieStore.getCookies()); - // Find cookies matching the given origin - final List matchedCookies = new ArrayList(); - final Date now = new Date(); - for (final Cookie cookie : cookies) { - if (!cookie.isExpired(now)) { - if (cookieSpec.match(cookie, cookieOrigin)) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Cookie " + cookie + " match " + cookieOrigin); - } - matchedCookies.add(cookie); - } - } else { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Cookie " + cookie + " expired"); - } - } - } - // Generate Cookie request headers - if (!matchedCookies.isEmpty()) { - final List

    headers = cookieSpec.formatCookies(matchedCookies); - for (final Header header : headers) { - request.addHeader(header); - } - } - - final int ver = cookieSpec.getVersion(); - if (ver > 0) { - boolean needVersionHeader = false; - for (final Cookie cookie : matchedCookies) { - if (ver != cookie.getVersion() || !(cookie instanceof SetCookie2)) { - needVersionHeader = true; - } - } - - if (needVersionHeader) { - final Header header = cookieSpec.getVersionHeader(); - if (header != null) { - // Advertise cookie version support - request.addHeader(header); - } - } - } - - // Stick the CookieSpec and CookieOrigin instances to the HTTP context - // so they could be obtained by the response interceptor - context.setAttribute(HttpClientContext.COOKIE_SPEC, cookieSpec); - context.setAttribute(HttpClientContext.COOKIE_ORIGIN, cookieOrigin); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestAuthCache.java b/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestAuthCache.java deleted file mode 100644 index d8bb3fbb..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestAuthCache.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.protocol; - -import java.io.IOException; - -import android.util.Log; - -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.annotation.Immutable; -import org.apache.http.auth.AuthProtocolState; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.AuthStateHC4; -import org.apache.http.auth.Credentials; -import org.apache.http.client.AuthCache; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.conn.routing.RouteInfo; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; - -/** - * Request interceptor that can preemptively authenticate against known hosts, - * if there is a cached {@link AuthScheme} instance in the local - * {@link AuthCache} associated with the given target or proxy host. - * - * @since 4.1 - */ -@Immutable -public class RequestAuthCache implements HttpRequestInterceptor { - - private final static String TAG = "HttpClient"; - - public RequestAuthCache() { - super(); - } - - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - Args.notNull(context, "HTTP context"); - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - final AuthCache authCache = clientContext.getAuthCache(); - if (authCache == null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Auth cache not set in the context"); - } - return; - } - - final CredentialsProvider credsProvider = clientContext.getCredentialsProvider(); - if (credsProvider == null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Credentials provider not set in the context"); - } - return; - } - - final RouteInfo route = clientContext.getHttpRoute(); - if (route == null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Route info not set in the context"); - } - return; - } - - HttpHost target = clientContext.getTargetHost(); - if (target == null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Target host not set in the context"); - } - return; - } - - if (target.getPort() < 0) { - target = new HttpHost( - target.getHostName(), - route.getTargetHost().getPort(), - target.getSchemeName()); - } - - final AuthStateHC4 targetState = clientContext.getTargetAuthState(); - if (targetState != null && targetState.getState() == AuthProtocolState.UNCHALLENGED) { - final AuthScheme authScheme = authCache.get(target); - if (authScheme != null) { - doPreemptiveAuth(target, authScheme, targetState, credsProvider); - } - } - - final HttpHost proxy = route.getProxyHost(); - final AuthStateHC4 proxyState = clientContext.getProxyAuthState(); - if (proxy != null && proxyState != null && proxyState.getState() == AuthProtocolState.UNCHALLENGED) { - final AuthScheme authScheme = authCache.get(proxy); - if (authScheme != null) { - doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider); - } - } - } - - private void doPreemptiveAuth( - final HttpHost host, - final AuthScheme authScheme, - final AuthStateHC4 authState, - final CredentialsProvider credsProvider) { - final String schemeName = authScheme.getSchemeName(); - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Re-using cached '" + schemeName + "' auth scheme for " + host); - } - - final AuthScope authScope = new AuthScope(host.getHostName(), host.getPort(), AuthScope.ANY_REALM, schemeName); - final Credentials creds = credsProvider.getCredentials(authScope); - - if (creds != null) { - if ("BASIC".equalsIgnoreCase(authScheme.getSchemeName())) { - authState.setState(AuthProtocolState.CHALLENGED); - } else { - authState.setState(AuthProtocolState.SUCCESS); - } - authState.update(authScheme, creds); - } else { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "No credentials for preemptive authentication"); - } - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestClientConnControl.java b/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestClientConnControl.java deleted file mode 100644 index 84279b5e..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestClientConnControl.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.protocol; - -import java.io.IOException; - -import android.util.Log; - -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.annotation.Immutable; -import org.apache.http.conn.routing.RouteInfo; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; - -/** - * This protocol interceptor is responsible for adding Connection - * or Proxy-Connection headers to the outgoing requests, which - * is essential for managing persistence of HTTP/1.0 connections. - * - * @since 4.0 - */ -@Immutable -public class RequestClientConnControl implements HttpRequestInterceptor { - - private final static String TAG = "HttpClient"; - - private static final String PROXY_CONN_DIRECTIVE = "Proxy-Connection"; - - public RequestClientConnControl() { - super(); - } - - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - - final String method = request.getRequestLine().getMethod(); - if (method.equalsIgnoreCase("CONNECT")) { - request.setHeader(PROXY_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); - return; - } - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - // Obtain the client connection (required) - final RouteInfo route = clientContext.getHttpRoute(); - if (route == null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Connection route not set in the context"); - } - return; - } - - if (route.getHopCount() == 1 || route.isTunnelled()) { - if (!request.containsHeader(HTTP.CONN_DIRECTIVE)) { - request.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); - } - } - if (route.getHopCount() == 2 && !route.isTunnelled()) { - if (!request.containsHeader(PROXY_CONN_DIRECTIVE)) { - request.addHeader(PROXY_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); - } - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestDefaultHeadersHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestDefaultHeadersHC4.java deleted file mode 100644 index 49d66f98..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestDefaultHeadersHC4.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.protocol; - -import java.io.IOException; -import java.util.Collection; - -import org.apache.http.Header; -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.annotation.Immutable; -import org.apache.http.client.params.ClientPNames; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; - -/** - * Request interceptor that adds default request headers. - * - * @since 4.0 - */ -@SuppressWarnings("deprecation") -@Immutable -public class RequestDefaultHeadersHC4 implements HttpRequestInterceptor { - - private final Collection defaultHeaders; - - /** - * @since 4.3 - */ - public RequestDefaultHeadersHC4(final Collection defaultHeaders) { - super(); - this.defaultHeaders = defaultHeaders; - } - - public RequestDefaultHeadersHC4() { - this(null); - } - - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - - final String method = request.getRequestLine().getMethod(); - if (method.equalsIgnoreCase("CONNECT")) { - return; - } - - // Add default headers - @SuppressWarnings("unchecked") - Collection defHeaders = (Collection) - request.getParams().getParameter(ClientPNames.DEFAULT_HEADERS); - if (defHeaders == null) { - defHeaders = this.defaultHeaders; - } - - if (defHeaders != null) { - for (final Header defHeader : defHeaders) { - request.addHeader(defHeader); - } - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestExpectContinue.java b/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestExpectContinue.java deleted file mode 100644 index 23817e68..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/RequestExpectContinue.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.protocol; - -import java.io.IOException; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.HttpVersion; -import org.apache.http.ProtocolVersion; -import org.apache.http.annotation.Immutable; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; - -/** - * RequestExpectContinue is responsible for enabling the 'expect-continue' - * handshake by adding Expect header. - *

    - * This interceptor takes into account {@link RequestConfig#isExpectContinueEnabled()} - * setting. - * - * @since 4.3 - */ -@Immutable -public class RequestExpectContinue implements HttpRequestInterceptor { - - public RequestExpectContinue() { - super(); - } - - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - - if (!request.containsHeader(HTTP.EXPECT_DIRECTIVE)) { - if (request instanceof HttpEntityEnclosingRequest) { - final ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); - final HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity(); - // Do not send the expect header if request body is known to be empty - if (entity != null - && entity.getContentLength() != 0 && !ver.lessEquals(HttpVersion.HTTP_1_0)) { - final HttpClientContext clientContext = HttpClientContext.adapt(context); - final RequestConfig config = clientContext.getRequestConfig(); - if (config.isExpectContinueEnabled()) { - request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); - } - } - } - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/ResponseContentEncoding.java b/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/ResponseContentEncoding.java deleted file mode 100644 index f55b5be3..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/ResponseContentEncoding.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.protocol; - -import java.io.IOException; -import java.util.Locale; - -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.HttpEntity; -import org.apache.http.HttpException; -import org.apache.http.HttpResponse; -import org.apache.http.HttpResponseInterceptor; -import org.apache.http.annotation.Immutable; -import org.apache.http.client.entity.DeflateDecompressingEntity; -import org.apache.http.client.entity.GzipDecompressingEntity; -import org.apache.http.protocol.HttpContext; - -/** - * {@link HttpResponseInterceptor} responsible for processing Content-Encoding - * responses. - *

    - * Instances of this class are stateless and immutable, therefore threadsafe. - * - * @since 4.1 - * - */ -@Immutable -public class ResponseContentEncoding implements HttpResponseInterceptor { - - public static final String UNCOMPRESSED = "http.client.response.uncompressed"; - - /** - * Handles the following {@code Content-Encoding}s by - * using the appropriate decompressor to wrap the response Entity: - *

      - *
    • gzip - see {@link GzipDecompressingEntity}
    • - *
    • deflate - see {@link DeflateDecompressingEntity}
    • - *
    • identity - no action needed
    • - *
    - * - * @param response the response which contains the entity - * @param context not currently used - * - * @throws HttpException if the {@code Content-Encoding} is none of the above - */ - public void process( - final HttpResponse response, - final HttpContext context) throws HttpException, IOException { - final HttpEntity entity = response.getEntity(); - - // entity can be null in case of 304 Not Modified, 204 No Content or similar - // check for zero length entity. - if (entity != null && entity.getContentLength() != 0) { - final Header ceheader = entity.getContentEncoding(); - if (ceheader != null) { - final HeaderElement[] codecs = ceheader.getElements(); - boolean uncompressed = false; - for (final HeaderElement codec : codecs) { - final String codecname = codec.getName().toLowerCase(Locale.ENGLISH); - if ("gzip".equals(codecname) || "x-gzip".equals(codecname)) { - response.setEntity(new GzipDecompressingEntity(response.getEntity())); - uncompressed = true; - break; - } else if ("deflate".equals(codecname)) { - response.setEntity(new DeflateDecompressingEntity(response.getEntity())); - uncompressed = true; - break; - } else if ("identity".equals(codecname)) { - - /* Don't need to transform the content - no-op */ - return; - } else { - throw new HttpException("Unsupported Content-Coding: " + codec.getName()); - } - } - if (uncompressed) { - response.removeHeaders("Content-Length"); - response.removeHeaders("Content-Encoding"); - response.removeHeaders("Content-MD5"); - } - } - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/ResponseProcessCookiesHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/ResponseProcessCookiesHC4.java deleted file mode 100644 index f99c452e..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/ResponseProcessCookiesHC4.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.protocol; - -import java.io.IOException; -import java.util.List; - -import android.util.Log; - -import org.apache.http.Header; -import org.apache.http.HeaderIterator; -import org.apache.http.HttpException; -import org.apache.http.HttpResponse; -import org.apache.http.HttpResponseInterceptor; -import org.apache.http.annotation.Immutable; -import org.apache.http.client.CookieStore; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.CookieSpec; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SM; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; - -/** - * Response interceptor that populates the current {@link CookieStore} with data - * contained in response cookies received in the given the HTTP response. - * - * @since 4.0 - */ -@Immutable -public class ResponseProcessCookiesHC4 implements HttpResponseInterceptor { - - private final static String TAG = "HttpClient"; - - public ResponseProcessCookiesHC4() { - super(); - } - - public void process(final HttpResponse response, final HttpContext context) - throws HttpException, IOException { - Args.notNull(response, "HTTP request"); - Args.notNull(context, "HTTP context"); - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - // Obtain actual CookieSpec instance - final CookieSpec cookieSpec = clientContext.getCookieSpec(); - if (cookieSpec == null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Cookie spec not specified in HTTP context"); - } - return; - } - // Obtain cookie store - final CookieStore cookieStore = clientContext.getCookieStore(); - if (cookieStore == null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Cookie store not specified in HTTP context"); - } - return; - } - // Obtain actual CookieOrigin instance - final CookieOrigin cookieOrigin = clientContext.getCookieOrigin(); - if (cookieOrigin == null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Cookie origin not specified in HTTP context"); - } - return; - } - HeaderIterator it = response.headerIterator(SM.SET_COOKIE); - processCookies(it, cookieSpec, cookieOrigin, cookieStore); - - // see if the cookie spec supports cookie versioning. - if (cookieSpec.getVersion() > 0) { - // process set-cookie2 headers. - // Cookie2 will replace equivalent Cookie instances - it = response.headerIterator(SM.SET_COOKIE2); - processCookies(it, cookieSpec, cookieOrigin, cookieStore); - } - } - - private void processCookies( - final HeaderIterator iterator, - final CookieSpec cookieSpec, - final CookieOrigin cookieOrigin, - final CookieStore cookieStore) { - while (iterator.hasNext()) { - final Header header = iterator.nextHeader(); - try { - final List cookies = cookieSpec.parse(header, cookieOrigin); - for (final Cookie cookie : cookies) { - try { - cookieSpec.validate(cookie, cookieOrigin); - cookieStore.addCookie(cookie); - - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Cookie accepted [" + formatCooke(cookie) + "]"); - } - } catch (final MalformedCookieException ex) { - if (Log.isLoggable(TAG, Log.WARN)) { - Log.w(TAG, "Cookie rejected [" + formatCooke(cookie) + "] " - + ex.getMessage()); - } - } - } - } catch (final MalformedCookieException ex) { - if (Log.isLoggable(TAG, Log.WARN)) { - Log.w(TAG, "Invalid cookie header: \"" - + header + "\". " + ex.getMessage()); - } - } - } - } - - private static String formatCooke(final Cookie cookie) { - final StringBuilder buf = new StringBuilder(); - buf.append(cookie.getName()); - buf.append("=\""); - String v = cookie.getValue(); - if (v.length() > 100) { - v = v.substring(0, 100) + "..."; - } - buf.append(v); - buf.append("\""); - buf.append(", version:"); - buf.append(Integer.toString(cookie.getVersion())); - buf.append(", domain:"); - buf.append(cookie.getDomain()); - buf.append(", path:"); - buf.append(cookie.getPath()); - buf.append(", expiry:"); - buf.append(cookie.getExpiryDate()); - return buf.toString(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/package-info.java deleted file mode 100644 index 61f8d817..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/protocol/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Client specific HTTP protocol handlers. - */ -package org.apache.http.client.protocol; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/CloneUtilsHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/client/utils/CloneUtilsHC4.java deleted file mode 100644 index 71a7ad81..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/CloneUtilsHC4.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.utils; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import org.apache.http.annotation.Immutable; - -/** - * A collection of utilities to workaround limitations of Java clone framework. - * - * @since 4.0 - */ -@Immutable -public class CloneUtilsHC4 { - - /** - * @since 4.3 - */ - public static T cloneObject(final T obj) throws CloneNotSupportedException { - if (obj == null) { - return null; - } - if (obj instanceof Cloneable) { - final Class clazz = obj.getClass (); - final Method m; - try { - m = clazz.getMethod("clone", (Class[]) null); - } catch (final NoSuchMethodException ex) { - throw new NoSuchMethodError(ex.getMessage()); - } - try { - @SuppressWarnings("unchecked") // OK because clone() preserves the class - final T result = (T) m.invoke(obj, (Object []) null); - return result; - } catch (final InvocationTargetException ex) { - final Throwable cause = ex.getCause(); - if (cause instanceof CloneNotSupportedException) { - throw ((CloneNotSupportedException) cause); - } else { - throw new Error("Unexpected exception", cause); - } - } catch (final IllegalAccessException ex) { - throw new IllegalAccessError(ex.getMessage()); - } - } else { - throw new CloneNotSupportedException(); - } - } - - public static Object clone(final Object obj) throws CloneNotSupportedException { - return cloneObject(obj); - } - - /** - * This class should not be instantiated. - */ - private CloneUtilsHC4() { - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/DateUtils.java b/lib/httpclient-android/src/main/java/org/apache/http/client/utils/DateUtils.java deleted file mode 100644 index 86f3c7eb..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/DateUtils.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.utils; - -import java.lang.ref.SoftReference; -import java.text.ParsePosition; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.TimeZone; - -import org.apache.http.annotation.Immutable; -import org.apache.http.util.Args; - -/** - * A utility class for parsing and formatting HTTP dates as used in cookies and - * other headers. This class handles dates as defined by RFC 2616 section - * 3.3.1 as well as some other common non-standard formats. - * - * @since 4.3 - */ -@Immutable -public final class DateUtils { - - /** - * Date format pattern used to parse HTTP date headers in RFC 1123 format. - */ - public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz"; - - /** - * Date format pattern used to parse HTTP date headers in RFC 1036 format. - */ - public static final String PATTERN_RFC1036 = "EEE, dd-MMM-yy HH:mm:ss zzz"; - - /** - * Date format pattern used to parse HTTP date headers in ANSI C - * asctime() format. - */ - public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy"; - - private static final String[] DEFAULT_PATTERNS = new String[] { - PATTERN_RFC1123, - PATTERN_RFC1036, - PATTERN_ASCTIME - }; - - private static final Date DEFAULT_TWO_DIGIT_YEAR_START; - - public static final TimeZone GMT = TimeZone.getTimeZone("GMT"); - - static { - final Calendar calendar = Calendar.getInstance(); - calendar.setTimeZone(GMT); - calendar.set(2000, Calendar.JANUARY, 1, 0, 0, 0); - calendar.set(Calendar.MILLISECOND, 0); - DEFAULT_TWO_DIGIT_YEAR_START = calendar.getTime(); - } - - /** - * Parses a date value. The formats used for parsing the date value are retrieved from - * the default http params. - * - * @param dateValue the date value to parse - * - * @return the parsed date or null if input could not be parsed - */ - public static Date parseDate(final String dateValue) { - return parseDate(dateValue, null, null); - } - - /** - * Parses the date value using the given date formats. - * - * @param dateValue the date value to parse - * @param dateFormats the date formats to use - * - * @return the parsed date or null if input could not be parsed - */ - public static Date parseDate(final String dateValue, final String[] dateFormats) { - return parseDate(dateValue, dateFormats, null); - } - - /** - * Parses the date value using the given date formats. - * - * @param dateValue the date value to parse - * @param dateFormats the date formats to use - * @param startDate During parsing, two digit years will be placed in the range - * startDate to startDate + 100 years. This value may - * be null. When null is given as a parameter, year - * 2000 will be used. - * - * @return the parsed date or null if input could not be parsed - */ - public static Date parseDate( - final String dateValue, - final String[] dateFormats, - final Date startDate) { - Args.notNull(dateValue, "Date value"); - final String[] localDateFormats = dateFormats != null ? dateFormats : DEFAULT_PATTERNS; - final Date localStartDate = startDate != null ? startDate : DEFAULT_TWO_DIGIT_YEAR_START; - String v = dateValue; - // trim single quotes around date if present - // see issue #5279 - if (v.length() > 1 && v.startsWith("'") && v.endsWith("'")) { - v = v.substring (1, v.length() - 1); - } - - for (final String dateFormat : localDateFormats) { - final SimpleDateFormat dateParser = DateFormatHolder.formatFor(dateFormat); - dateParser.set2DigitYearStart(localStartDate); - final ParsePosition pos = new ParsePosition(0); - final Date result = dateParser.parse(v, pos); - if (pos.getIndex() != 0) { - return result; - } - } - return null; - } - - /** - * Formats the given date according to the RFC 1123 pattern. - * - * @param date The date to format. - * @return An RFC 1123 formatted date string. - * - * @see #PATTERN_RFC1123 - */ - public static String formatDate(final Date date) { - return formatDate(date, PATTERN_RFC1123); - } - - /** - * Formats the given date according to the specified pattern. The pattern - * must conform to that used by the {@link SimpleDateFormat simple date - * format} class. - * - * @param date The date to format. - * @param pattern The pattern to use for formatting the date. - * @return A formatted date string. - * - * @throws IllegalArgumentException If the given date pattern is invalid. - * - * @see SimpleDateFormat - */ - public static String formatDate(final Date date, final String pattern) { - Args.notNull(date, "Date"); - Args.notNull(pattern, "Pattern"); - final SimpleDateFormat formatter = DateFormatHolder.formatFor(pattern); - return formatter.format(date); - } - - /** - * Clears thread-local variable containing {@link java.text.DateFormat} cache. - * - * @since 4.3 - */ - public static void clearThreadLocal() { - DateFormatHolder.clearThreadLocal(); - } - - /** This class should not be instantiated. */ - private DateUtils() { - } - - /** - * A factory for {@link SimpleDateFormat}s. The instances are stored in a - * threadlocal way because SimpleDateFormat is not threadsafe as noted in - * {@link SimpleDateFormat its javadoc}. - * - */ - final static class DateFormatHolder { - - private static final ThreadLocal>> - THREADLOCAL_FORMATS = new ThreadLocal>>() { - - @Override - protected SoftReference> initialValue() { - return new SoftReference>( - new HashMap()); - } - - }; - - /** - * creates a {@link SimpleDateFormat} for the requested format string. - * - * @param pattern - * a non-null format String according to - * {@link SimpleDateFormat}. The format is not checked against - * null since all paths go through - * {@link DateUtils}. - * @return the requested format. This simple dateformat should not be used - * to {@link SimpleDateFormat#applyPattern(String) apply} to a - * different pattern. - */ - public static SimpleDateFormat formatFor(final String pattern) { - final SoftReference> ref = THREADLOCAL_FORMATS.get(); - Map formats = ref.get(); - if (formats == null) { - formats = new HashMap(); - THREADLOCAL_FORMATS.set( - new SoftReference>(formats)); - } - - SimpleDateFormat format = formats.get(pattern); - if (format == null) { - format = new SimpleDateFormat(pattern, Locale.US); - format.setTimeZone(TimeZone.getTimeZone("GMT")); - formats.put(pattern, format); - } - - return format; - } - - public static void clearThreadLocal() { - THREADLOCAL_FORMATS.remove(); - } - - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/HttpClientUtils.java b/lib/httpclient-android/src/main/java/org/apache/http/client/utils/HttpClientUtils.java deleted file mode 100644 index 3d2c68b0..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/HttpClientUtils.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.utils; - -import java.io.Closeable; -import java.io.IOException; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.util.EntityUtilsHC4; - -/** - * Convenience methods for closing response and client objects. - * - * @since 4.2 - */ -public class HttpClientUtils { - - private HttpClientUtils() { - } - - /** - * Unconditionally close a response. - *

    - * Example Code: - * - *

    -     * HttpResponse httpResponse = null;
    -     * try {
    -     *     httpResponse = httpClient.execute(httpGet);
    -     * } catch (Exception e) {
    -     *     // error handling
    -     * } finally {
    -     *     HttpClientUtils.closeQuietly(httpResponse);
    -     * }
    -     * 
    - * - * @param response - * the HttpResponse to release resources, may be null or already - * closed. - * - * @since 4.2 - */ - public static void closeQuietly(final HttpResponse response) { - if (response != null) { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - try { - EntityUtilsHC4.consume(entity); - } catch (final IOException ex) { - } - } - } - } - - /** - * Unconditionally close a response. - *

    - * Example Code: - * - *

    -     * HttpResponse httpResponse = null;
    -     * try {
    -     *     httpResponse = httpClient.execute(httpGet);
    -     * } catch (Exception e) {
    -     *     // error handling
    -     * } finally {
    -     *     HttpClientUtils.closeQuietly(httpResponse);
    -     * }
    -     * 
    - * - * @param response - * the HttpResponse to release resources, may be null or already - * closed. - * - * @since 4.3 - */ - public static void closeQuietly(final CloseableHttpResponse response) { - if (response != null) { - try { - try { - EntityUtilsHC4.consume(response.getEntity()); - } finally { - response.close(); - } - } catch (final IOException ignore) { - } - } - } - - /** - * Unconditionally close a httpClient. Shuts down the underlying connection - * manager and releases the resources. - *

    - * Example Code: - * - *

    -     * HttpClient httpClient = HttpClients.createDefault();
    -     * try {
    -     *   httpClient.execute(request);
    -     * } catch (Exception e) {
    -     *   // error handling
    -     * } finally {
    -     *   HttpClientUtils.closeQuietly(httpClient);
    -     * }
    -     * 
    - * - * @param httpClient - * the HttpClient to close, may be null or already closed. - * @since 4.2 - */ - public static void closeQuietly(final HttpClient httpClient) { - if (httpClient != null) { - if (httpClient instanceof Closeable) { - try { - ((Closeable) httpClient).close(); - } catch (final IOException ignore) { - } - } - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/Idn.java b/lib/httpclient-android/src/main/java/org/apache/http/client/utils/Idn.java deleted file mode 100644 index 41c0e2b2..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/Idn.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.utils; - -/** - * Abstraction of international domain name (IDN) conversion. - * - * @since 4.0 - */ -public interface Idn { - /** - * Converts a name from its punycode representation to Unicode. - * The name may be a single hostname or a dot-separated qualified domain name. - * @param punycode the Punycode representation - * @return the Unicode domain name - */ - String toUnicode(String punycode); -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/JdkIdn.java b/lib/httpclient-android/src/main/java/org/apache/http/client/utils/JdkIdn.java deleted file mode 100644 index 2f0b0861..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/JdkIdn.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.utils; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import org.apache.http.annotation.Immutable; - -/** - * Uses the java.net.IDN class through reflection. - * - * @since 4.0 - */ -@Immutable -public class JdkIdn implements Idn { - private final Method toUnicode; - - /** - * - * @throws ClassNotFoundException if java.net.IDN is not available - */ - public JdkIdn() throws ClassNotFoundException { - final Class clazz = Class.forName("java.net.IDN"); - try { - toUnicode = clazz.getMethod("toUnicode", String.class); - } catch (final SecurityException e) { - // doesn't happen - throw new IllegalStateException(e.getMessage(), e); - } catch (final NoSuchMethodException e) { - // doesn't happen - throw new IllegalStateException(e.getMessage(), e); - } - } - - public String toUnicode(final String punycode) { - try { - return (String) toUnicode.invoke(null, punycode); - } catch (final IllegalAccessException e) { - throw new IllegalStateException(e.getMessage(), e); - } catch (final InvocationTargetException e) { - final Throwable t = e.getCause(); - throw new RuntimeException(t.getMessage(), t); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/Punycode.java b/lib/httpclient-android/src/main/java/org/apache/http/client/utils/Punycode.java deleted file mode 100644 index 750f503f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/Punycode.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.utils; - -import org.apache.http.annotation.Immutable; - -/** - * Facade that provides conversion between Unicode and Punycode domain names. - * It will use an appropriate implementation. - * - * @since 4.0 - */ -@Immutable -public class Punycode { - private static final Idn impl; - static { - Idn _impl; - try { - _impl = new JdkIdn(); - } catch (final Exception e) { - _impl = new Rfc3492Idn(); - } - impl = _impl; - } - - public static String toUnicode(final String punycode) { - return impl.toUnicode(punycode); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/Rfc3492Idn.java b/lib/httpclient-android/src/main/java/org/apache/http/client/utils/Rfc3492Idn.java deleted file mode 100644 index 293d9b06..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/Rfc3492Idn.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.utils; - -import java.util.StringTokenizer; - -import org.apache.http.annotation.Immutable; - -/** - * Implementation from pseudo code in RFC 3492. - * - * @since 4.0 - */ -@Immutable -public class Rfc3492Idn implements Idn { - private static final int base = 36; - private static final int tmin = 1; - private static final int tmax = 26; - private static final int skew = 38; - private static final int damp = 700; - private static final int initial_bias = 72; - private static final int initial_n = 128; - private static final char delimiter = '-'; - private static final String ACE_PREFIX = "xn--"; - - private int adapt(final int delta, final int numpoints, final boolean firsttime) { - int d = delta; - if (firsttime) { - d = d / damp; - } else { - d = d / 2; - } - d = d + (d / numpoints); - int k = 0; - while (d > ((base - tmin) * tmax) / 2) { - d = d / (base - tmin); - k = k + base; - } - return k + (((base - tmin + 1) * d) / (d + skew)); - } - - private int digit(final char c) { - if ((c >= 'A') && (c <= 'Z')) { - return (c - 'A'); - } - if ((c >= 'a') && (c <= 'z')) { - return (c - 'a'); - } - if ((c >= '0') && (c <= '9')) { - return (c - '0') + 26; - } - throw new IllegalArgumentException("illegal digit: "+ c); - } - - public String toUnicode(final String punycode) { - final StringBuilder unicode = new StringBuilder(punycode.length()); - final StringTokenizer tok = new StringTokenizer(punycode, "."); - while (tok.hasMoreTokens()) { - String t = tok.nextToken(); - if (unicode.length() > 0) { - unicode.append('.'); - } - if (t.startsWith(ACE_PREFIX)) { - t = decode(t.substring(4)); - } - unicode.append(t); - } - return unicode.toString(); - } - - protected String decode(final String s) { - String input = s; - int n = initial_n; - int i = 0; - int bias = initial_bias; - final StringBuilder output = new StringBuilder(input.length()); - final int lastdelim = input.lastIndexOf(delimiter); - if (lastdelim != -1) { - output.append(input.subSequence(0, lastdelim)); - input = input.substring(lastdelim + 1); - } - - while (input.length() > 0) { - final int oldi = i; - int w = 1; - for (int k = base;; k += base) { - if (input.length() == 0) { - break; - } - final char c = input.charAt(0); - input = input.substring(1); - final int digit = digit(c); - i = i + digit * w; // FIXME fail on overflow - final int t; - if (k <= bias + tmin) { - t = tmin; - } else if (k >= bias + tmax) { - t = tmax; - } else { - t = k - bias; - } - if (digit < t) { - break; - } - w = w * (base - t); // FIXME fail on overflow - } - bias = adapt(i - oldi, output.length() + 1, (oldi == 0)); - n = n + i / (output.length() + 1); // FIXME fail on overflow - i = i % (output.length() + 1); - // {if n is a basic code point then fail} - output.insert(i, (char) n); - i++; - } - return output.toString(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/URIBuilder.java b/lib/httpclient-android/src/main/java/org/apache/http/client/utils/URIBuilder.java deleted file mode 100644 index 03240022..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/URIBuilder.java +++ /dev/null @@ -1,490 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.utils; - -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.http.Consts; -import org.apache.http.NameValuePair; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.conn.util.InetAddressUtilsHC4; -import org.apache.http.message.BasicNameValuePair; - -/** - * Builder for {@link URI} instances. - * - * @since 4.2 - */ -@NotThreadSafe -public class URIBuilder { - - private String scheme; - private String encodedSchemeSpecificPart; - private String encodedAuthority; - private String userInfo; - private String encodedUserInfo; - private String host; - private int port; - private String path; - private String encodedPath; - private String encodedQuery; - private List queryParams; - private String query; - private String fragment; - private String encodedFragment; - - /** - * Constructs an empty instance. - */ - public URIBuilder() { - super(); - this.port = -1; - } - - /** - * Construct an instance from the string which must be a valid URI. - * - * @param string a valid URI in string form - * @throws URISyntaxException if the input is not a valid URI - */ - public URIBuilder(final String string) throws URISyntaxException { - super(); - digestURI(new URI(string)); - } - - /** - * Construct an instance from the provided URI. - * @param uri - */ - public URIBuilder(final URI uri) { - super(); - digestURI(uri); - } - - private List parseQuery(final String query, final Charset charset) { - if (query != null && query.length() > 0) { - return URLEncodedUtilsHC4.parse(query, charset); - } - return null; - } - - /** - * Builds a {@link URI} instance. - */ - public URI build() throws URISyntaxException { - return new URI(buildString()); - } - - private String buildString() { - final StringBuilder sb = new StringBuilder(); - if (this.scheme != null) { - sb.append(this.scheme).append(':'); - } - if (this.encodedSchemeSpecificPart != null) { - sb.append(this.encodedSchemeSpecificPart); - } else { - if (this.encodedAuthority != null) { - sb.append("//").append(this.encodedAuthority); - } else if (this.host != null) { - sb.append("//"); - if (this.encodedUserInfo != null) { - sb.append(this.encodedUserInfo).append("@"); - } else if (this.userInfo != null) { - sb.append(encodeUserInfo(this.userInfo)).append("@"); - } - if (InetAddressUtilsHC4.isIPv6Address(this.host)) { - sb.append("[").append(this.host).append("]"); - } else { - sb.append(this.host); - } - if (this.port >= 0) { - sb.append(":").append(this.port); - } - } - if (this.encodedPath != null) { - sb.append(normalizePath(this.encodedPath)); - } else if (this.path != null) { - sb.append(encodePath(normalizePath(this.path))); - } - if (this.encodedQuery != null) { - sb.append("?").append(this.encodedQuery); - } else if (this.queryParams != null) { - sb.append("?").append(encodeUrlForm(this.queryParams)); - } else if (this.query != null) { - sb.append("?").append(encodeUric(this.query)); - } - } - if (this.encodedFragment != null) { - sb.append("#").append(this.encodedFragment); - } else if (this.fragment != null) { - sb.append("#").append(encodeUric(this.fragment)); - } - return sb.toString(); - } - - private void digestURI(final URI uri) { - this.scheme = uri.getScheme(); - this.encodedSchemeSpecificPart = uri.getRawSchemeSpecificPart(); - this.encodedAuthority = uri.getRawAuthority(); - this.host = uri.getHost(); - this.port = uri.getPort(); - this.encodedUserInfo = uri.getRawUserInfo(); - this.userInfo = uri.getUserInfo(); - this.encodedPath = uri.getRawPath(); - this.path = uri.getPath(); - this.encodedQuery = uri.getRawQuery(); - this.queryParams = parseQuery(uri.getRawQuery(), Consts.UTF_8); - this.encodedFragment = uri.getRawFragment(); - this.fragment = uri.getFragment(); - } - - private String encodeUserInfo(final String userInfo) { - return URLEncodedUtilsHC4.encUserInfo(userInfo, Consts.UTF_8); - } - - private String encodePath(final String path) { - return URLEncodedUtilsHC4.encPath(path, Consts.UTF_8); - } - - private String encodeUrlForm(final List params) { - return URLEncodedUtilsHC4.format(params, Consts.UTF_8); - } - - private String encodeUric(final String fragment) { - return URLEncodedUtilsHC4.encUric(fragment, Consts.UTF_8); - } - - /** - * Sets URI scheme. - */ - public URIBuilder setScheme(final String scheme) { - this.scheme = scheme; - return this; - } - - /** - * Sets URI user info. The value is expected to be unescaped and may contain non ASCII - * characters. - */ - public URIBuilder setUserInfo(final String userInfo) { - this.userInfo = userInfo; - this.encodedSchemeSpecificPart = null; - this.encodedAuthority = null; - this.encodedUserInfo = null; - return this; - } - - /** - * Sets URI user info as a combination of username and password. These values are expected to - * be unescaped and may contain non ASCII characters. - */ - public URIBuilder setUserInfo(final String username, final String password) { - return setUserInfo(username + ':' + password); - } - - /** - * Sets URI host. - */ - public URIBuilder setHost(final String host) { - this.host = host; - this.encodedSchemeSpecificPart = null; - this.encodedAuthority = null; - return this; - } - - /** - * Sets URI port. - */ - public URIBuilder setPort(final int port) { - this.port = port < 0 ? -1 : port; - this.encodedSchemeSpecificPart = null; - this.encodedAuthority = null; - return this; - } - - /** - * Sets URI path. The value is expected to be unescaped and may contain non ASCII characters. - */ - public URIBuilder setPath(final String path) { - this.path = path; - this.encodedSchemeSpecificPart = null; - this.encodedPath = null; - return this; - } - - /** - * Removes URI query. - */ - public URIBuilder removeQuery() { - this.queryParams = null; - this.query = null; - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - return this; - } - - /** - * Sets URI query. - *

    - * The value is expected to be encoded form data. - * - * @deprecated (4.3) use {@link #setParameters(List)} or {@link #setParameters(NameValuePair...)} - * - * @see URLEncodedUtilsHC4#parse - */ - @Deprecated - public URIBuilder setQuery(final String query) { - this.queryParams = parseQuery(query, Consts.UTF_8); - this.query = null; - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - return this; - } - - /** - * Sets URI query parameters. The parameter name / values are expected to be unescaped - * and may contain non ASCII characters. - *

    - * Please note query parameters and custom query component are mutually exclusive. This method - * will remove custom query if present. - * - * @since 4.3 - */ - public URIBuilder setParameters(final List nvps) { - if (this.queryParams == null) { - this.queryParams = new ArrayList(); - } else { - this.queryParams.clear(); - } - this.queryParams.addAll(nvps); - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - this.query = null; - return this; - } - - /** - * Adds URI query parameters. The parameter name / values are expected to be unescaped - * and may contain non ASCII characters. - *

    - * Please note query parameters and custom query component are mutually exclusive. This method - * will remove custom query if present. - * - * @since 4.3 - */ - public URIBuilder addParameters(final List nvps) { - if (this.queryParams == null) { - this.queryParams = new ArrayList(); - } - this.queryParams.addAll(nvps); - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - this.query = null; - return this; - } - - /** - * Sets URI query parameters. The parameter name / values are expected to be unescaped - * and may contain non ASCII characters. - *

    - * Please note query parameters and custom query component are mutually exclusive. This method - * will remove custom query if present. - * - * @since 4.3 - */ - public URIBuilder setParameters(final NameValuePair... nvps) { - if (this.queryParams == null) { - this.queryParams = new ArrayList(); - } else { - this.queryParams.clear(); - } - for (final NameValuePair nvp: nvps) { - this.queryParams.add(nvp); - } - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - this.query = null; - return this; - } - - /** - * Adds parameter to URI query. The parameter name and value are expected to be unescaped - * and may contain non ASCII characters. - *

    - * Please note query parameters and custom query component are mutually exclusive. This method - * will remove custom query if present. - */ - public URIBuilder addParameter(final String param, final String value) { - if (this.queryParams == null) { - this.queryParams = new ArrayList(); - } - this.queryParams.add(new BasicNameValuePair(param, value)); - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - this.query = null; - return this; - } - - /** - * Sets parameter of URI query overriding existing value if set. The parameter name and value - * are expected to be unescaped and may contain non ASCII characters. - *

    - * Please note query parameters and custom query component are mutually exclusive. This method - * will remove custom query if present. - */ - public URIBuilder setParameter(final String param, final String value) { - if (this.queryParams == null) { - this.queryParams = new ArrayList(); - } - if (!this.queryParams.isEmpty()) { - for (final Iterator it = this.queryParams.iterator(); it.hasNext(); ) { - final NameValuePair nvp = it.next(); - if (nvp.getName().equals(param)) { - it.remove(); - } - } - } - this.queryParams.add(new BasicNameValuePair(param, value)); - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - this.query = null; - return this; - } - - /** - * Clears URI query parameters. - * - * @since 4.3 - */ - public URIBuilder clearParameters() { - this.queryParams = null; - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - return this; - } - - /** - * Sets custom URI query. The value is expected to be unescaped and may contain non ASCII - * characters. - *

    - * Please note query parameters and custom query component are mutually exclusive. This method - * will remove query parameters if present. - * - * @since 4.3 - */ - public URIBuilder setCustomQuery(final String query) { - this.query = query; - this.encodedQuery = null; - this.encodedSchemeSpecificPart = null; - this.queryParams = null; - return this; - } - - /** - * Sets URI fragment. The value is expected to be unescaped and may contain non ASCII - * characters. - */ - public URIBuilder setFragment(final String fragment) { - this.fragment = fragment; - this.encodedFragment = null; - return this; - } - - /** - * @since 4.3 - */ - public boolean isAbsolute() { - return this.scheme != null; - } - - /** - * @since 4.3 - */ - public boolean isOpaque() { - return this.path == null; - } - - public String getScheme() { - return this.scheme; - } - - public String getUserInfo() { - return this.userInfo; - } - - public String getHost() { - return this.host; - } - - public int getPort() { - return this.port; - } - - public String getPath() { - return this.path; - } - - public List getQueryParams() { - if (this.queryParams != null) { - return new ArrayList(this.queryParams); - } else { - return new ArrayList(); - } - } - - public String getFragment() { - return this.fragment; - } - - @Override - public String toString() { - return buildString(); - } - - private static String normalizePath(final String path) { - String s = path; - if (s == null) { - return null; - } - int n = 0; - for (; n < s.length(); n++) { - if (s.charAt(n) != '/') { - break; - } - } - if (n > 1) { - s = s.substring(n - 1); - } - return s; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/URIUtilsHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/client/utils/URIUtilsHC4.java deleted file mode 100644 index b4d566d8..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/URIUtilsHC4.java +++ /dev/null @@ -1,428 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.client.utils; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Locale; -import java.util.Stack; - -import org.apache.http.HttpHost; -import org.apache.http.annotation.Immutable; -import org.apache.http.util.Args; -import org.apache.http.util.TextUtils; - -/** - * A collection of utilities for {@link URI URIs}, to workaround - * bugs within the class or for ease-of-use features. - * - * @since 4.0 - */ -@Immutable -public class URIUtilsHC4 { - - /** - * Constructs a {@link URI} using all the parameters. This should be - * used instead of - * {@link URI#URI(String, String, String, int, String, String, String)} - * or any of the other URI multi-argument URI constructors. - * - * @param scheme - * Scheme name - * @param host - * Host name - * @param port - * Port number - * @param path - * Path - * @param query - * Query - * @param fragment - * Fragment - * - * @throws URISyntaxException - * If both a scheme and a path are given but the path is - * relative, if the URI string constructed from the given - * components violates RFC 2396, or if the authority - * component of the string is present but cannot be parsed - * as a server-based authority - * - * @deprecated (4.2) use {@link URIBuilder}. - */ - @Deprecated - public static URI createURI( - final String scheme, - final String host, - final int port, - final String path, - final String query, - final String fragment) throws URISyntaxException { - final StringBuilder buffer = new StringBuilder(); - if (host != null) { - if (scheme != null) { - buffer.append(scheme); - buffer.append("://"); - } - buffer.append(host); - if (port > 0) { - buffer.append(':'); - buffer.append(port); - } - } - if (path == null || !path.startsWith("/")) { - buffer.append('/'); - } - if (path != null) { - buffer.append(path); - } - if (query != null) { - buffer.append('?'); - buffer.append(query); - } - if (fragment != null) { - buffer.append('#'); - buffer.append(fragment); - } - return new URI(buffer.toString()); - } - - /** - * A convenience method for creating a new {@link URI} whose scheme, host - * and port are taken from the target host, but whose path, query and - * fragment are taken from the existing URI. The fragment is only used if - * dropFragment is false. The path is set to "/" if not explicitly specified. - * - * @param uri - * Contains the path, query and fragment to use. - * @param target - * Contains the scheme, host and port to use. - * @param dropFragment - * True if the fragment should not be copied. - * - * @throws URISyntaxException - * If the resulting URI is invalid. - */ - public static URI rewriteURI( - final URI uri, - final HttpHost target, - final boolean dropFragment) throws URISyntaxException { - Args.notNull(uri, "URI"); - if (uri.isOpaque()) { - return uri; - } - final URIBuilder uribuilder = new URIBuilder(uri); - if (target != null) { - uribuilder.setScheme(target.getSchemeName()); - uribuilder.setHost(target.getHostName()); - uribuilder.setPort(target.getPort()); - } else { - uribuilder.setScheme(null); - uribuilder.setHost(null); - uribuilder.setPort(-1); - } - if (dropFragment) { - uribuilder.setFragment(null); - } - if (TextUtils.isEmpty(uribuilder.getPath())) { - uribuilder.setPath("/"); - } - return uribuilder.build(); - } - - /** - * A convenience method for - * {@link URIUtilsHC4#rewriteURI(URI, HttpHost, boolean)} that always keeps the - * fragment. - */ - public static URI rewriteURI( - final URI uri, - final HttpHost target) throws URISyntaxException { - return rewriteURI(uri, target, false); - } - - /** - * A convenience method that creates a new {@link URI} whose scheme, host, port, path, - * query are taken from the existing URI, dropping any fragment or user-information. - * The path is set to "/" if not explicitly specified. The existing URI is returned - * unmodified if it has no fragment or user-information and has a path. - * - * @param uri - * original URI. - * @throws URISyntaxException - * If the resulting URI is invalid. - */ - public static URI rewriteURI(final URI uri) throws URISyntaxException { - Args.notNull(uri, "URI"); - if (uri.isOpaque()) { - return uri; - } - final URIBuilder uribuilder = new URIBuilder(uri); - if (uribuilder.getUserInfo() != null) { - uribuilder.setUserInfo(null); - } - if (TextUtils.isEmpty(uribuilder.getPath())) { - uribuilder.setPath("/"); - } - if (uribuilder.getHost() != null) { - uribuilder.setHost(uribuilder.getHost().toLowerCase(Locale.ENGLISH)); - } - uribuilder.setFragment(null); - return uribuilder.build(); - } - - /** - * Resolves a URI reference against a base URI. Work-around for bug in - * java.net.URI () - * - * @param baseURI the base URI - * @param reference the URI reference - * @return the resulting URI - */ - public static URI resolve(final URI baseURI, final String reference) { - return URIUtilsHC4.resolve(baseURI, URI.create(reference)); - } - - /** - * Resolves a URI reference against a base URI. Work-around for bugs in - * java.net.URI (e.g. ) - * - * @param baseURI the base URI - * @param reference the URI reference - * @return the resulting URI - */ - public static URI resolve(final URI baseURI, final URI reference){ - Args.notNull(baseURI, "Base URI"); - Args.notNull(reference, "Reference URI"); - URI ref = reference; - final String s = ref.toString(); - if (s.startsWith("?")) { - return resolveReferenceStartingWithQueryString(baseURI, ref); - } - final boolean emptyReference = s.length() == 0; - if (emptyReference) { - ref = URI.create("#"); - } - URI resolved = baseURI.resolve(ref); - if (emptyReference) { - final String resolvedString = resolved.toString(); - resolved = URI.create(resolvedString.substring(0, - resolvedString.indexOf('#'))); - } - return normalizeSyntax(resolved); - } - - /** - * Resolves a reference starting with a query string. - * - * @param baseURI the base URI - * @param reference the URI reference starting with a query string - * @return the resulting URI - */ - private static URI resolveReferenceStartingWithQueryString( - final URI baseURI, final URI reference) { - String baseUri = baseURI.toString(); - baseUri = baseUri.indexOf('?') > -1 ? - baseUri.substring(0, baseUri.indexOf('?')) : baseUri; - return URI.create(baseUri + reference.toString()); - } - - /** - * Removes dot segments according to RFC 3986, section 5.2.4 and - * Syntax-Based Normalization according to RFC 3986, section 6.2.2. - * - * @param uri the original URI - * @return the URI without dot segments - */ - private static URI normalizeSyntax(final URI uri) { - if (uri.isOpaque() || uri.getAuthority() == null) { - // opaque and file: URIs - return uri; - } - Args.check(uri.isAbsolute(), "Base URI must be absolute"); - final String path = uri.getPath() == null ? "" : uri.getPath(); - final String[] inputSegments = path.split("/"); - final Stack outputSegments = new Stack(); - for (final String inputSegment : inputSegments) { - if ((inputSegment.length() == 0) - || (".".equals(inputSegment))) { - // Do nothing - } else if ("..".equals(inputSegment)) { - if (!outputSegments.isEmpty()) { - outputSegments.pop(); - } - } else { - outputSegments.push(inputSegment); - } - } - final StringBuilder outputBuffer = new StringBuilder(); - for (final String outputSegment : outputSegments) { - outputBuffer.append('/').append(outputSegment); - } - if (path.lastIndexOf('/') == path.length() - 1) { - // path.endsWith("/") || path.equals("") - outputBuffer.append('/'); - } - try { - final String scheme = uri.getScheme().toLowerCase(Locale.ENGLISH); - final String auth = uri.getAuthority().toLowerCase(Locale.ENGLISH); - final URI ref = new URI(scheme, auth, outputBuffer.toString(), - null, null); - if (uri.getQuery() == null && uri.getFragment() == null) { - return ref; - } - final StringBuilder normalized = new StringBuilder( - ref.toASCIIString()); - if (uri.getQuery() != null) { - // query string passed through unchanged - normalized.append('?').append(uri.getRawQuery()); - } - if (uri.getFragment() != null) { - // fragment passed through unchanged - normalized.append('#').append(uri.getRawFragment()); - } - return URI.create(normalized.toString()); - } catch (final URISyntaxException e) { - throw new IllegalArgumentException(e); - } - } - - /** - * Extracts target host from the given {@link URI}. - * - * @param uri - * @return the target host if the URI is absolute or null if the URI is - * relative or does not contain a valid host name. - * - * @since 4.1 - */ - public static HttpHost extractHost(final URI uri) { - if (uri == null) { - return null; - } - HttpHost target = null; - if (uri.isAbsolute()) { - int port = uri.getPort(); // may be overridden later - String host = uri.getHost(); - if (host == null) { // normal parse failed; let's do it ourselves - // authority does not seem to care about the valid character-set for host names - host = uri.getAuthority(); - if (host != null) { - // Strip off any leading user credentials - final int at = host.indexOf('@'); - if (at >= 0) { - if (host.length() > at+1 ) { - host = host.substring(at+1); - } else { - host = null; // @ on its own - } - } - // Extract the port suffix, if present - if (host != null) { - final int colon = host.indexOf(':'); - if (colon >= 0) { - final int pos = colon + 1; - int len = 0; - for (int i = pos; i < host.length(); i++) { - if (Character.isDigit(host.charAt(i))) { - len++; - } else { - break; - } - } - if (len > 0) { - try { - port = Integer.parseInt(host.substring(pos, pos + len)); - } catch (final NumberFormatException ex) { - } - } - host = host.substring(0, colon); - } - } - } - } - final String scheme = uri.getScheme(); - if (!TextUtils.isBlank(host)) { - target = new HttpHost(host, port, scheme); - } - } - return target; - } - - /** - * Derives the interpreted (absolute) URI that was used to generate the last - * request. This is done by extracting the request-uri and target origin for - * the last request and scanning all the redirect locations for the last - * fragment identifier, then combining the result into a {@link URI}. - * - * @param originalURI - * original request before any redirects - * @param target - * if the last URI is relative, it is resolved against this target, - * or null if not available. - * @param redirects - * collection of redirect locations since the original request - * or null if not available. - * @return interpreted (absolute) URI - */ - public static URI resolve( - final URI originalURI, - final HttpHost target, - final List redirects) throws URISyntaxException { - Args.notNull(originalURI, "Request URI"); - final URIBuilder uribuilder; - if (redirects == null || redirects.isEmpty()) { - uribuilder = new URIBuilder(originalURI); - } else { - uribuilder = new URIBuilder(redirects.get(redirects.size() - 1)); - String frag = uribuilder.getFragment(); - // read interpreted fragment identifier from redirect locations - for (int i = redirects.size() - 1; frag == null && i >= 0; i--) { - frag = redirects.get(i).getFragment(); - } - uribuilder.setFragment(frag); - } - // read interpreted fragment identifier from original request - if (uribuilder.getFragment() == null) { - uribuilder.setFragment(originalURI.getFragment()); - } - // last target origin - if (target != null && !uribuilder.isAbsolute()) { - uribuilder.setScheme(target.getSchemeName()); - uribuilder.setHost(target.getHostName()); - uribuilder.setPort(target.getPort()); - } - return uribuilder.build(); - } - - /** - * This class should not be instantiated. - */ - private URIUtilsHC4() { - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/URLEncodedUtilsHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/client/utils/URLEncodedUtilsHC4.java deleted file mode 100644 index f8f71015..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/URLEncodedUtilsHC4.java +++ /dev/null @@ -1,628 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.client.utils; - -import java.io.IOException; -import java.net.URI; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.BitSet; -import java.util.Collections; -import java.util.List; -import java.util.Scanner; - -import org.apache.http.Consts; -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.HttpEntity; -import org.apache.http.NameValuePair; -import org.apache.http.annotation.Immutable; -import org.apache.http.entity.ContentType; -import org.apache.http.message.BasicHeaderValueParserHC4; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.message.ParserCursor; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.CharArrayBuffer; -import org.apache.http.util.EntityUtilsHC4; - -/** - * A collection of utilities for encoding URLs. - * - * @since 4.0 - */ -@Immutable -public class URLEncodedUtilsHC4 { - - /** - * The default HTML form content type. - */ - public static final String CONTENT_TYPE = "application/x-www-form-urlencoded"; - - private static final char QP_SEP_A = '&'; - private static final char QP_SEP_S = ';'; - private static final String NAME_VALUE_SEPARATOR = "="; - - /** - * Returns a list of {@link NameValuePair NameValuePairs} as built from the URI's query portion. For example, a URI - * of http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three NameValuePairs, one for a=1, one for - * b=2, and one for c=3. By convention, {@code '&'} and {@code ';'} are accepted as parameter separators. - *

    - * This is typically useful while parsing an HTTP PUT. - * - * This API is currently only used for testing. - * - * @param uri - * URI to parse - * @param charset - * Charset name to use while parsing the query - * @return a list of {@link NameValuePair} as built from the URI's query portion. - */ - public static List parse(final URI uri, final String charset) { - final String query = uri.getRawQuery(); - if (query != null && query.length() > 0) { - final List result = new ArrayList(); - final Scanner scanner = new Scanner(query); - parse(result, scanner, QP_SEP_PATTERN, charset); - return result; - } - return Collections.emptyList(); - } - - /** - * Returns a list of {@link NameValuePair NameValuePairs} as parsed from an {@link HttpEntity}. The encoding is - * taken from the entity's Content-Encoding header. - *

    - * This is typically used while parsing an HTTP POST. - * - * @param entity - * The entity to parse - * @return a list of {@link NameValuePair} as built from the URI's query portion. - * @throws IOException - * If there was an exception getting the entity's data. - */ - public static List parse( - final HttpEntity entity) throws IOException { - final ContentType contentType = ContentType.get(entity); - if (contentType != null && contentType.getMimeType().equalsIgnoreCase(CONTENT_TYPE)) { - final String content = EntityUtilsHC4.toString(entity, Consts.ASCII); - if (content != null && content.length() > 0) { - Charset charset = contentType.getCharset(); - if (charset == null) { - charset = Charset.forName(HTTP.DEFAULT_CONTENT_CHARSET); - } - return parse(content, charset, QP_SEPS); - } - } - return Collections.emptyList(); - } - - /** - * Returns true if the entity's Content-Type header is - * application/x-www-form-urlencoded. - */ - public static boolean isEncoded(final HttpEntity entity) { - final Header h = entity.getContentType(); - if (h != null) { - final HeaderElement[] elems = h.getElements(); - if (elems.length > 0) { - final String contentType = elems[0].getName(); - return contentType.equalsIgnoreCase(CONTENT_TYPE); - } - } - return false; - } - - /** - * Adds all parameters within the Scanner to the list of parameters, as encoded by - * encoding. For example, a scanner containing the string a=1&b=2&c=3 would add the - * {@link NameValuePair NameValuePairs} a=1, b=2, and c=3 to the list of parameters. By convention, {@code '&'} and - * {@code ';'} are accepted as parameter separators. - * - * @param parameters - * List to add parameters to. - * @param scanner - * Input that contains the parameters to parse. - * @param charset - * Encoding to use when decoding the parameters. - */ - public static void parse( - final List parameters, - final Scanner scanner, - final String charset) { - parse(parameters, scanner, QP_SEP_PATTERN, charset); - } - - /** - * Adds all parameters within the Scanner to the list of - * parameters, as encoded by encoding. For - * example, a scanner containing the string a=1&b=2&c=3 would - * add the {@link NameValuePair NameValuePairs} a=1, b=2, and c=3 to the - * list of parameters. - * - * @param parameters - * List to add parameters to. - * @param scanner - * Input that contains the parameters to parse. - * @param parameterSepartorPattern - * The Pattern string for parameter separators, by convention {@code "[&;]"} - * @param charset - * Encoding to use when decoding the parameters. - */ - public static void parse( - final List parameters, - final Scanner scanner, - final String parameterSepartorPattern, - final String charset) { - scanner.useDelimiter(parameterSepartorPattern); - while (scanner.hasNext()) { - String name = null; - String value = null; - final String token = scanner.next(); - final int i = token.indexOf(NAME_VALUE_SEPARATOR); - if (i != -1) { - name = decodeFormFields(token.substring(0, i).trim(), charset); - value = decodeFormFields(token.substring(i + 1).trim(), charset); - } else { - name = decodeFormFields(token.trim(), charset); - } - parameters.add(new BasicNameValuePair(name, value)); - } - } - - /** - * Query parameter separators. - */ - private static final char[] QP_SEPS = new char[] { QP_SEP_A, QP_SEP_S }; - - /** - * Query parameter separator pattern. - */ - private static final String QP_SEP_PATTERN = "[" + new String(QP_SEPS) + "]"; - - /** - * Returns a list of {@link NameValuePair NameValuePairs} as parsed from the given string using the given character - * encoding. By convention, {@code '&'} and {@code ';'} are accepted as parameter separators. - * - * @param s - * text to parse. - * @param charset - * Encoding to use when decoding the parameters. - * @return a list of {@link NameValuePair} as built from the URI's query portion. - * - * @since 4.2 - */ - public static List parse(final String s, final Charset charset) { - return parse(s, charset, QP_SEPS); - } - - /** - * Returns a list of {@link NameValuePair NameValuePairs} as parsed from the given string using the given character - * encoding. - * - * @param s - * text to parse. - * @param charset - * Encoding to use when decoding the parameters. - * @param parameterSeparator - * The characters used to separate parameters, by convention, {@code '&'} and {@code ';'}. - * @return a list of {@link NameValuePair} as built from the URI's query portion. - * - * @since 4.3 - */ - public static List parse(final String s, final Charset charset, final char... parameterSeparator) { - if (s == null) { - return Collections.emptyList(); - } - final BasicHeaderValueParserHC4 parser = BasicHeaderValueParserHC4.INSTANCE; - final CharArrayBuffer buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - final ParserCursor cursor = new ParserCursor(0, buffer.length()); - final List list = new ArrayList(); - while (!cursor.atEnd()) { - final NameValuePair nvp = parser.parseNameValuePair(buffer, cursor, parameterSeparator); - if (nvp.getName().length() > 0) { - list.add(new BasicNameValuePair( - decodeFormFields(nvp.getName(), charset), - decodeFormFields(nvp.getValue(), charset))); - } - } - return list; - } - - /** - * Returns a String that is suitable for use as an {@code application/x-www-form-urlencoded} - * list of parameters in an HTTP PUT or HTTP POST. - * - * @param parameters The parameters to include. - * @param charset The encoding to use. - * @return An {@code application/x-www-form-urlencoded} string - */ - public static String format( - final List parameters, - final String charset) { - return format(parameters, QP_SEP_A, charset); - } - - /** - * Returns a String that is suitable for use as an {@code application/x-www-form-urlencoded} - * list of parameters in an HTTP PUT or HTTP POST. - * - * @param parameters The parameters to include. - * @param parameterSeparator The parameter separator, by convention, {@code '&'} or {@code ';'}. - * @param charset The encoding to use. - * @return An {@code application/x-www-form-urlencoded} string - * - * @since 4.3 - */ - public static String format( - final List parameters, - final char parameterSeparator, - final String charset) { - final StringBuilder result = new StringBuilder(); - for (final NameValuePair parameter : parameters) { - final String encodedName = encodeFormFields(parameter.getName(), charset); - final String encodedValue = encodeFormFields(parameter.getValue(), charset); - if (result.length() > 0) { - result.append(parameterSeparator); - } - result.append(encodedName); - if (encodedValue != null) { - result.append(NAME_VALUE_SEPARATOR); - result.append(encodedValue); - } - } - return result.toString(); - } - - /** - * Returns a String that is suitable for use as an {@code application/x-www-form-urlencoded} - * list of parameters in an HTTP PUT or HTTP POST. - * - * @param parameters The parameters to include. - * @param charset The encoding to use. - * @return An {@code application/x-www-form-urlencoded} string - * - * @since 4.2 - */ - public static String format( - final Iterable parameters, - final Charset charset) { - return format(parameters, QP_SEP_A, charset); - } - - /** - * Returns a String that is suitable for use as an {@code application/x-www-form-urlencoded} - * list of parameters in an HTTP PUT or HTTP POST. - * - * @param parameters The parameters to include. - * @param parameterSeparator The parameter separator, by convention, {@code '&'} or {@code ';'}. - * @param charset The encoding to use. - * @return An {@code application/x-www-form-urlencoded} string - * - * @since 4.3 - */ - public static String format( - final Iterable parameters, - final char parameterSeparator, - final Charset charset) { - final StringBuilder result = new StringBuilder(); - for (final NameValuePair parameter : parameters) { - final String encodedName = encodeFormFields(parameter.getName(), charset); - final String encodedValue = encodeFormFields(parameter.getValue(), charset); - if (result.length() > 0) { - result.append(parameterSeparator); - } - result.append(encodedName); - if (encodedValue != null) { - result.append(NAME_VALUE_SEPARATOR); - result.append(encodedValue); - } - } - return result.toString(); - } - - /** - * Unreserved characters, i.e. alphanumeric, plus: {@code _ - ! . ~ ' ( ) *} - *

    - * This list is the same as the {@code unreserved} list in - * RFC 2396 - */ - private static final BitSet UNRESERVED = new BitSet(256); - /** - * Punctuation characters: , ; : $ & + = - *

    - * These are the additional characters allowed by userinfo. - */ - private static final BitSet PUNCT = new BitSet(256); - /** Characters which are safe to use in userinfo, - * i.e. {@link #UNRESERVED} plus {@link #PUNCT}uation */ - private static final BitSet USERINFO = new BitSet(256); - /** Characters which are safe to use in a path, - * i.e. {@link #UNRESERVED} plus {@link #PUNCT}uation plus / @ */ - private static final BitSet PATHSAFE = new BitSet(256); - /** Characters which are safe to use in a query or a fragment, - * i.e. {@link #RESERVED} plus {@link #UNRESERVED} */ - private static final BitSet URIC = new BitSet(256); - - /** - * Reserved characters, i.e. {@code ;/?:@&=+$,[]} - *

    - * This list is the same as the {@code reserved} list in - * RFC 2396 - * as augmented by - * RFC 2732 - */ - private static final BitSet RESERVED = new BitSet(256); - - - /** - * Safe characters for x-www-form-urlencoded data, as per java.net.URLEncoder and browser behaviour, - * i.e. alphanumeric plus {@code "-", "_", ".", "*"} - */ - private static final BitSet URLENCODER = new BitSet(256); - - static { - // unreserved chars - // alpha characters - for (int i = 'a'; i <= 'z'; i++) { - UNRESERVED.set(i); - } - for (int i = 'A'; i <= 'Z'; i++) { - UNRESERVED.set(i); - } - // numeric characters - for (int i = '0'; i <= '9'; i++) { - UNRESERVED.set(i); - } - UNRESERVED.set('_'); // these are the charactes of the "mark" list - UNRESERVED.set('-'); - UNRESERVED.set('.'); - UNRESERVED.set('*'); - URLENCODER.or(UNRESERVED); // skip remaining unreserved characters - UNRESERVED.set('!'); - UNRESERVED.set('~'); - UNRESERVED.set('\''); - UNRESERVED.set('('); - UNRESERVED.set(')'); - // punct chars - PUNCT.set(','); - PUNCT.set(';'); - PUNCT.set(':'); - PUNCT.set('$'); - PUNCT.set('&'); - PUNCT.set('+'); - PUNCT.set('='); - // Safe for userinfo - USERINFO.or(UNRESERVED); - USERINFO.or(PUNCT); - - // URL path safe - PATHSAFE.or(UNRESERVED); - PATHSAFE.set('/'); // segment separator - PATHSAFE.set(';'); // param separator - PATHSAFE.set(':'); // rest as per list in 2396, i.e. : @ & = + $ , - PATHSAFE.set('@'); - PATHSAFE.set('&'); - PATHSAFE.set('='); - PATHSAFE.set('+'); - PATHSAFE.set('$'); - PATHSAFE.set(','); - - RESERVED.set(';'); - RESERVED.set('/'); - RESERVED.set('?'); - RESERVED.set(':'); - RESERVED.set('@'); - RESERVED.set('&'); - RESERVED.set('='); - RESERVED.set('+'); - RESERVED.set('$'); - RESERVED.set(','); - RESERVED.set('['); // added by RFC 2732 - RESERVED.set(']'); // added by RFC 2732 - - URIC.or(RESERVED); - URIC.or(UNRESERVED); - } - - private static final int RADIX = 16; - - private static String urlEncode( - final String content, - final Charset charset, - final BitSet safechars, - final boolean blankAsPlus) { - if (content == null) { - return null; - } - final StringBuilder buf = new StringBuilder(); - final ByteBuffer bb = charset.encode(content); - while (bb.hasRemaining()) { - final int b = bb.get() & 0xff; - if (safechars.get(b)) { - buf.append((char) b); - } else if (blankAsPlus && b == ' ') { - buf.append('+'); - } else { - buf.append("%"); - final char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, RADIX)); - final char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, RADIX)); - buf.append(hex1); - buf.append(hex2); - } - } - return buf.toString(); - } - - /** - * Decode/unescape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true. - * - * @param content the portion to decode - * @param charset the charset to use - * @param plusAsBlank if {@code true}, then convert '+' to space (e.g. for www-url-form-encoded content), otherwise leave as is. - * @return encoded string - */ - private static String urlDecode( - final String content, - final Charset charset, - final boolean plusAsBlank) { - if (content == null) { - return null; - } - final ByteBuffer bb = ByteBuffer.allocate(content.length()); - final CharBuffer cb = CharBuffer.wrap(content); - while (cb.hasRemaining()) { - final char c = cb.get(); - if (c == '%' && cb.remaining() >= 2) { - final char uc = cb.get(); - final char lc = cb.get(); - final int u = Character.digit(uc, 16); - final int l = Character.digit(lc, 16); - if (u != -1 && l != -1) { - bb.put((byte) ((u << 4) + l)); - } else { - bb.put((byte) '%'); - bb.put((byte) uc); - bb.put((byte) lc); - } - } else if (plusAsBlank && c == '+') { - bb.put((byte) ' '); - } else { - bb.put((byte) c); - } - } - bb.flip(); - return charset.decode(bb).toString(); - } - - /** - * Decode/unescape www-url-form-encoded content. - * - * @param content the content to decode, will decode '+' as space - * @param charset the charset to use - * @return encoded string - */ - private static String decodeFormFields (final String content, final String charset) { - if (content == null) { - return null; - } - return urlDecode(content, charset != null ? Charset.forName(charset) : Consts.UTF_8, true); - } - - /** - * Decode/unescape www-url-form-encoded content. - * - * @param content the content to decode, will decode '+' as space - * @param charset the charset to use - * @return encoded string - */ - private static String decodeFormFields (final String content, final Charset charset) { - if (content == null) { - return null; - } - return urlDecode(content, charset != null ? charset : Consts.UTF_8, true); - } - - /** - * Encode/escape www-url-form-encoded content. - *

    - * Uses the {@link #URLENCODER} set of characters, rather than - * the {@link #UNRSERVED} set; this is for compatibilty with previous - * releases, URLEncoder.encode() and most browsers. - * - * @param content the content to encode, will convert space to '+' - * @param charset the charset to use - * @return encoded string - */ - private static String encodeFormFields(final String content, final String charset) { - if (content == null) { - return null; - } - return urlEncode(content, charset != null ? Charset.forName(charset) : Consts.UTF_8, URLENCODER, true); - } - - /** - * Encode/escape www-url-form-encoded content. - *

    - * Uses the {@link #URLENCODER} set of characters, rather than - * the {@link #UNRSERVED} set; this is for compatibilty with previous - * releases, URLEncoder.encode() and most browsers. - * - * @param content the content to encode, will convert space to '+' - * @param charset the charset to use - * @return encoded string - */ - private static String encodeFormFields (final String content, final Charset charset) { - if (content == null) { - return null; - } - return urlEncode(content, charset != null ? charset : Consts.UTF_8, URLENCODER, true); - } - - /** - * Encode a String using the {@link #USERINFO} set of characters. - *

    - * Used by URIBuilder to encode the userinfo segment. - * - * @param content the string to encode, does not convert space to '+' - * @param charset the charset to use - * @return the encoded string - */ - static String encUserInfo(final String content, final Charset charset) { - return urlEncode(content, charset, USERINFO, false); - } - - /** - * Encode a String using the {@link #URIC} set of characters. - *

    - * Used by URIBuilder to encode the query and fragment segments. - * - * @param content the string to encode, does not convert space to '+' - * @param charset the charset to use - * @return the encoded string - */ - static String encUric(final String content, final Charset charset) { - return urlEncode(content, charset, URIC, false); - } - - /** - * Encode a String using the {@link #PATHSAFE} set of characters. - *

    - * Used by URIBuilder to encode path segments. - * - * @param content the string to encode, does not convert space to '+' - * @param charset the charset to use - * @return the encoded string - */ - static String encPath(final String content, final Charset charset) { - return urlEncode(content, charset, PATHSAFE, false); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/client/utils/package-info.java deleted file mode 100644 index 1e3e15f9..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/client/utils/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Client utility classes. - */ -package org.apache.http.client.utils; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/concurrent/BasicFuture.java b/lib/httpclient-android/src/main/java/org/apache/http/concurrent/BasicFuture.java deleted file mode 100644 index 5c59dd3e..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/concurrent/BasicFuture.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.concurrent; - -import org.apache.http.util.Args; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -/** - * Basic implementation of the {@link Future} interface. BasicFuture - * can be put into a completed state by invoking any of the following methods: - * {@link #cancel()}, {@link #failed(Exception)}, or {@link #completed(Object)}. - * - * @param the future result type of an asynchronous operation. - * @since 4.2 - */ -public class BasicFuture implements Future, Cancellable { - - private final FutureCallback callback; - - private volatile boolean completed; - private volatile boolean cancelled; - private volatile T result; - private volatile Exception ex; - - public BasicFuture(final FutureCallback callback) { - super(); - this.callback = callback; - } - - public boolean isCancelled() { - return this.cancelled; - } - - public boolean isDone() { - return this.completed; - } - - private T getResult() throws ExecutionException { - if (this.ex != null) { - throw new ExecutionException(this.ex); - } - return this.result; - } - - public synchronized T get() throws InterruptedException, ExecutionException { - while (!this.completed) { - wait(); - } - return getResult(); - } - - public synchronized T get(final long timeout, final TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException { - Args.notNull(unit, "Time unit"); - final long msecs = unit.toMillis(timeout); - final long startTime = (msecs <= 0) ? 0 : System.currentTimeMillis(); - long waitTime = msecs; - if (this.completed) { - return getResult(); - } else if (waitTime <= 0) { - throw new TimeoutException(); - } else { - for (;;) { - wait(waitTime); - if (this.completed) { - return getResult(); - } else { - waitTime = msecs - (System.currentTimeMillis() - startTime); - if (waitTime <= 0) { - throw new TimeoutException(); - } - } - } - } - } - - public boolean completed(final T result) { - synchronized(this) { - if (this.completed) { - return false; - } - this.completed = true; - this.result = result; - notifyAll(); - } - if (this.callback != null) { - this.callback.completed(result); - } - return true; - } - - public boolean failed(final Exception exception) { - synchronized(this) { - if (this.completed) { - return false; - } - this.completed = true; - this.ex = exception; - notifyAll(); - } - if (this.callback != null) { - this.callback.failed(exception); - } - return true; - } - - public boolean cancel(final boolean mayInterruptIfRunning) { - synchronized(this) { - if (this.completed) { - return false; - } - this.completed = true; - this.cancelled = true; - notifyAll(); - } - if (this.callback != null) { - this.callback.cancelled(); - } - return true; - } - - public boolean cancel() { - return cancel(true); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/concurrent/Cancellable.java b/lib/httpclient-android/src/main/java/org/apache/http/concurrent/Cancellable.java deleted file mode 100644 index e7869bfd..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/concurrent/Cancellable.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.concurrent; - -/** - * A Cancellable represents a process or an operation that can be - * canceled. - * - * @since 4.2 - */ -public interface Cancellable { - - boolean cancel(); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/concurrent/FutureCallback.java b/lib/httpclient-android/src/main/java/org/apache/http/concurrent/FutureCallback.java deleted file mode 100644 index 234c47b6..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/concurrent/FutureCallback.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.concurrent; - -/** - * A callback interface that gets invoked upon completion of - * a {@link java.util.concurrent.Future}. - * - * @param the future result type returned by this callback. - * @since 4.2 - */ -public interface FutureCallback { - - void completed(T result); - - void failed(Exception ex); - - void cancelled(); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/concurrent/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/concurrent/package-info.java deleted file mode 100644 index c08ea14f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/concurrent/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Core concurrency APIs. - */ -package org.apache.http.concurrent; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/config/ConnectionConfig.java b/lib/httpclient-android/src/main/java/org/apache/http/config/ConnectionConfig.java deleted file mode 100644 index 2c466c39..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/config/ConnectionConfig.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.config; - -import java.nio.charset.Charset; -import java.nio.charset.CodingErrorAction; - -import org.apache.http.Consts; -import org.apache.http.annotation.Immutable; -import org.apache.http.util.Args; - -/** - * HTTP connection configuration. - * - * @since 4.3 - */ -@Immutable -public class ConnectionConfig implements Cloneable { - - public static final ConnectionConfig DEFAULT = new Builder().build(); - - private final int bufferSize; - private final int fragmentSizeHint; - private final Charset charset; - private final CodingErrorAction malformedInputAction; - private final CodingErrorAction unmappableInputAction; - private final MessageConstraints messageConstraints; - - ConnectionConfig( - final int bufferSize, - final int fragmentSizeHint, - final Charset charset, - final CodingErrorAction malformedInputAction, - final CodingErrorAction unmappableInputAction, - final MessageConstraints messageConstraints) { - super(); - this.bufferSize = bufferSize; - this.fragmentSizeHint = fragmentSizeHint; - this.charset = charset; - this.malformedInputAction = malformedInputAction; - this.unmappableInputAction = unmappableInputAction; - this.messageConstraints = messageConstraints; - } - - public int getBufferSize() { - return bufferSize; - } - - public int getFragmentSizeHint() { - return fragmentSizeHint; - } - - public Charset getCharset() { - return charset; - } - - public CodingErrorAction getMalformedInputAction() { - return malformedInputAction; - } - - public CodingErrorAction getUnmappableInputAction() { - return unmappableInputAction; - } - - public MessageConstraints getMessageConstraints() { - return messageConstraints; - } - - @Override - protected ConnectionConfig clone() throws CloneNotSupportedException { - return (ConnectionConfig) super.clone(); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("[bufferSize=").append(this.bufferSize) - .append(", fragmentSizeHint=").append(this.fragmentSizeHint) - .append(", charset=").append(this.charset) - .append(", malformedInputAction=").append(this.malformedInputAction) - .append(", unmappableInputAction=").append(this.unmappableInputAction) - .append(", messageConstraints=").append(this.messageConstraints) - .append("]"); - return builder.toString(); - } - - public static ConnectionConfig.Builder custom() { - return new Builder(); - } - - public static ConnectionConfig.Builder copy(final ConnectionConfig config) { - Args.notNull(config, "Connection config"); - return new Builder() - .setCharset(config.getCharset()) - .setMalformedInputAction(config.getMalformedInputAction()) - .setUnmappableInputAction(config.getUnmappableInputAction()) - .setMessageConstraints(config.getMessageConstraints()); - } - - public static class Builder { - - private int bufferSize; - private int fragmentSizeHint; - private Charset charset; - private CodingErrorAction malformedInputAction; - private CodingErrorAction unmappableInputAction; - private MessageConstraints messageConstraints; - - Builder() { - this.fragmentSizeHint = -1; - } - - public Builder setBufferSize(final int bufferSize) { - this.bufferSize = bufferSize; - return this; - } - - public Builder setFragmentSizeHint(final int fragmentSizeHint) { - this.fragmentSizeHint = fragmentSizeHint; - return this; - } - - public Builder setCharset(final Charset charset) { - this.charset = charset; - return this; - } - - public Builder setMalformedInputAction(final CodingErrorAction malformedInputAction) { - this.malformedInputAction = malformedInputAction; - if (malformedInputAction != null && this.charset == null) { - this.charset = Consts.ASCII; - } - return this; - } - - public Builder setUnmappableInputAction(final CodingErrorAction unmappableInputAction) { - this.unmappableInputAction = unmappableInputAction; - if (unmappableInputAction != null && this.charset == null) { - this.charset = Consts.ASCII; - } - return this; - } - - public Builder setMessageConstraints(final MessageConstraints messageConstraints) { - this.messageConstraints = messageConstraints; - return this; - } - - public ConnectionConfig build() { - Charset cs = charset; - if (cs == null && (malformedInputAction != null || unmappableInputAction != null)) { - cs = Consts.ASCII; - } - final int bufSize = this.bufferSize > 0 ? this.bufferSize : 8 * 1024; - final int fragmentHintSize = this.fragmentSizeHint >= 0 ? this.fragmentSizeHint : bufSize; - return new ConnectionConfig( - bufSize, - fragmentHintSize, - cs, - malformedInputAction, - unmappableInputAction, - messageConstraints); - } - - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/config/Lookup.java b/lib/httpclient-android/src/main/java/org/apache/http/config/Lookup.java deleted file mode 100644 index ff3759ce..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/config/Lookup.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.config; - - -/** - * Generic lookup by low-case string ID. - * - * @since 4.3 - */ -public interface Lookup { - - I lookup(String name); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/config/MessageConstraints.java b/lib/httpclient-android/src/main/java/org/apache/http/config/MessageConstraints.java deleted file mode 100644 index 5c65e23e..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/config/MessageConstraints.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.config; - -import org.apache.http.util.Args; - -/** - * HTTP Message constraints: line length and header count. - * - * @since 4.3 - */ -public class MessageConstraints implements Cloneable { - - public static final MessageConstraints DEFAULT = new Builder().build(); - - private final int maxLineLength; - private final int maxHeaderCount; - - MessageConstraints(final int maxLineLength, final int maxHeaderCount) { - super(); - this.maxLineLength = maxLineLength; - this.maxHeaderCount = maxHeaderCount; - } - - public int getMaxLineLength() { - return maxLineLength; - } - - public int getMaxHeaderCount() { - return maxHeaderCount; - } - - @Override - protected MessageConstraints clone() throws CloneNotSupportedException { - return (MessageConstraints) super.clone(); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("[maxLineLength=").append(maxLineLength) - .append(", maxHeaderCount=").append(maxHeaderCount) - .append("]"); - return builder.toString(); - } - - public static MessageConstraints lineLen(final int max) { - return new MessageConstraints(Args.notNegative(max, "Max line length"), -1); - } - - public static MessageConstraints.Builder custom() { - return new Builder(); - } - - public static MessageConstraints.Builder copy(final MessageConstraints config) { - Args.notNull(config, "Message constraints"); - return new Builder() - .setMaxHeaderCount(config.getMaxHeaderCount()) - .setMaxLineLength(config.getMaxLineLength()); - } - - public static class Builder { - - private int maxLineLength; - private int maxHeaderCount; - - Builder() { - this.maxLineLength = -1; - this.maxHeaderCount = -1; - } - - public Builder setMaxLineLength(final int maxLineLength) { - this.maxLineLength = maxLineLength; - return this; - } - - public Builder setMaxHeaderCount(final int maxHeaderCount) { - this.maxHeaderCount = maxHeaderCount; - return this; - } - - public MessageConstraints build() { - return new MessageConstraints(maxLineLength, maxHeaderCount); - } - - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/config/Registry.java b/lib/httpclient-android/src/main/java/org/apache/http/config/Registry.java deleted file mode 100644 index d79c71d7..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/config/Registry.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.config; - -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.http.annotation.ThreadSafe; - -/** - * Generic registry of items keyed by low-case string ID. - * - * @since 4.3 - */ -@ThreadSafe -public final class Registry implements Lookup { - - private final Map map; - - Registry(final Map map) { - super(); - this.map = new ConcurrentHashMap(map); - } - - public I lookup(final String key) { - if (key == null) { - return null; - } - return map.get(key.toLowerCase(Locale.US)); - } - - @Override - public String toString() { - return map.toString(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/config/RegistryBuilder.java b/lib/httpclient-android/src/main/java/org/apache/http/config/RegistryBuilder.java deleted file mode 100644 index e5687da4..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/config/RegistryBuilder.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.config; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.util.Args; - -/** - * Builder for {@link Registry} instances. - * - * @since 4.3 - */ -@NotThreadSafe -public final class RegistryBuilder { - - private final Map items; - - public static RegistryBuilder create() { - return new RegistryBuilder(); - } - - RegistryBuilder() { - super(); - this.items = new HashMap(); - } - - public RegistryBuilder register(final String id, final I item) { - Args.notEmpty(id, "ID"); - Args.notNull(item, "Item"); - items.put(id.toLowerCase(Locale.US), item); - return this; - } - - public Registry build() { - return new Registry(items); - } - - @Override - public String toString() { - return items.toString(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/config/SocketConfig.java b/lib/httpclient-android/src/main/java/org/apache/http/config/SocketConfig.java deleted file mode 100644 index bea618fe..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/config/SocketConfig.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.config; - -import org.apache.http.annotation.Immutable; -import org.apache.http.util.Args; - -/** - * Socket configuration. - * - * @since 4.3 - */ -@Immutable -public class SocketConfig implements Cloneable { - - public static final SocketConfig DEFAULT = new Builder().build(); - - private final int soTimeout; - private final boolean soReuseAddress; - private final int soLinger; - private final boolean soKeepAlive; - private final boolean tcpNoDelay; - - SocketConfig( - final int soTimeout, - final boolean soReuseAddress, - final int soLinger, - final boolean soKeepAlive, - final boolean tcpNoDelay) { - super(); - this.soTimeout = soTimeout; - this.soReuseAddress = soReuseAddress; - this.soLinger = soLinger; - this.soKeepAlive = soKeepAlive; - this.tcpNoDelay = tcpNoDelay; - } - - /** - * Determines the default socket timeout value for non-blocking I/O operations. - *

    - * Default: 0 (no timeout) - * - * @see java.net.SocketOptions#SO_TIMEOUT - */ - public int getSoTimeout() { - return soTimeout; - } - - /** - * Determines the default value of the {@link java.net.SocketOptions#SO_REUSEADDR} parameter - * for newly created sockets. - *

    - * Default: false - * - * @see java.net.SocketOptions#SO_REUSEADDR - */ - public boolean isSoReuseAddress() { - return soReuseAddress; - } - - /** - * Determines the default value of the {@link java.net.SocketOptions#SO_LINGER} parameter - * for newly created sockets. - *

    - * Default: -1 - * - * @see java.net.SocketOptions#SO_LINGER - */ - public int getSoLinger() { - return soLinger; - } - - /** - * Determines the default value of the {@link java.net.SocketOptions#SO_KEEPALIVE} parameter - * for newly created sockets. - *

    - * Default: -1 - * - * @see java.net.SocketOptions#SO_KEEPALIVE - */ - public boolean isSoKeepAlive() { - return this.soKeepAlive; - } - - /** - * Determines the default value of the {@link java.net.SocketOptions#TCP_NODELAY} parameter - * for newly created sockets. - *

    - * Default: false - * - * @see java.net.SocketOptions#TCP_NODELAY - */ - public boolean isTcpNoDelay() { - return tcpNoDelay; - } - - @Override - protected SocketConfig clone() throws CloneNotSupportedException { - return (SocketConfig) super.clone(); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("[soTimeout=").append(this.soTimeout) - .append(", soReuseAddress=").append(this.soReuseAddress) - .append(", soLinger=").append(this.soLinger) - .append(", soKeepAlive=").append(this.soKeepAlive) - .append(", tcpNoDelay=").append(this.tcpNoDelay) - .append("]"); - return builder.toString(); - } - - public static SocketConfig.Builder custom() { - return new Builder(); - } - - public static SocketConfig.Builder copy(final SocketConfig config) { - Args.notNull(config, "Socket config"); - return new Builder() - .setSoTimeout(config.getSoTimeout()) - .setSoReuseAddress(config.isSoReuseAddress()) - .setSoLinger(config.getSoLinger()) - .setSoKeepAlive(config.isSoKeepAlive()) - .setTcpNoDelay(config.isTcpNoDelay()); - } - - public static class Builder { - - private int soTimeout; - private boolean soReuseAddress; - private int soLinger; - private boolean soKeepAlive; - private boolean tcpNoDelay; - - Builder() { - this.soLinger = -1; - this.tcpNoDelay = true; - } - - public Builder setSoTimeout(final int soTimeout) { - this.soTimeout = soTimeout; - return this; - } - - public Builder setSoReuseAddress(final boolean soReuseAddress) { - this.soReuseAddress = soReuseAddress; - return this; - } - - public Builder setSoLinger(final int soLinger) { - this.soLinger = soLinger; - return this; - } - - public Builder setSoKeepAlive(final boolean soKeepAlive) { - this.soKeepAlive = soKeepAlive; - return this; - } - - public Builder setTcpNoDelay(final boolean tcpNoDelay) { - this.tcpNoDelay = tcpNoDelay; - return this; - } - - public SocketConfig build() { - return new SocketConfig(soTimeout, soReuseAddress, soLinger, soKeepAlive, tcpNoDelay); - } - - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/config/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/config/package-info.java deleted file mode 100644 index 74387794..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/config/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Core configuration APIs. - */ -package org.apache.http.config; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ConnectionRequest.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ConnectionRequest.java deleted file mode 100644 index a6c6af92..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ConnectionRequest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; - -import org.apache.http.HttpClientConnection; -import org.apache.http.concurrent.Cancellable; - -/** - * Represents a request for a {@link HttpClientConnection} whose life cycle - * is managed by a connection manager. - * - * @since 4.3 - */ -public interface ConnectionRequest extends Cancellable { - - /** - * Obtains a connection within a given time. - * This method will block until a connection becomes available, - * the timeout expires, or the connection manager is shut down. - * Timeouts are handled with millisecond precision. - * - * If {@link #cancel()} is called while this is blocking or - * before this began, an {@link InterruptedException} will - * be thrown. - * - * @param timeout the timeout, 0 or negative for no timeout - * @param tunit the unit for the timeout, - * may be null only if there is no timeout - * - * @return a connection that can be used to communicate - * along the given route - * - * @throws ConnectionPoolTimeoutException - * in case of a timeout - * @throws InterruptedException - * if the calling thread is interrupted while waiting - */ - HttpClientConnection get(long timeout, TimeUnit tunit) - throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException; - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/DnsResolver.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/DnsResolver.java deleted file mode 100644 index c4501f39..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/DnsResolver.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.conn; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -/** - * Users may implement this interface to override the normal DNS lookup offered - * by the OS. - * - * @since 4.2 - */ -public interface DnsResolver { - - /** - * Returns the IP address for the specified host name, or null if the given - * host is not recognized or the associated IP address cannot be used to - * build an InetAddress instance. - * - * @see InetAddress - * - * @param host - * The host name to be resolved by this resolver. - * @return The IP address associated to the given host name, or null if the - * host name is not known by the implementation class. - */ - InetAddress[] resolve(String host) throws UnknownHostException; - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/EofSensorInputStreamHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/EofSensorInputStreamHC4.java deleted file mode 100644 index 13a8f348..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/EofSensorInputStreamHC4.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.conn; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.util.Args; - -/** - * A stream wrapper that triggers actions on {@link #close close()} and EOF. - * Primarily used to auto-release an underlying managed connection when the response - * body is consumed or no longer needed. - * - * @see EofSensorWatcher - * - * @since 4.0 - */ -// don't use FilterInputStream as the base class, we'd have to -// override markSupported(), mark(), and reset() to disable them -@NotThreadSafe -public class EofSensorInputStreamHC4 extends InputStream implements ConnectionReleaseTrigger { - - /** - * The wrapped input stream, while accessible. - * The value changes to null when the wrapped stream - * becomes inaccessible. - */ - protected InputStream wrappedStream; - - /** - * Indicates whether this stream itself is closed. - * If it isn't, but {@link #wrappedStream wrappedStream} - * is null, we're running in EOF mode. - * All read operations will indicate EOF without accessing - * the underlying stream. After closing this stream, read - * operations will trigger an {@link IOException IOException}. - * - * @see #isReadAllowed isReadAllowed - */ - private boolean selfClosed; - - /** The watcher to be notified, if any. */ - private final EofSensorWatcher eofWatcher; - - /** - * Creates a new EOF sensor. - * If no watcher is passed, the underlying stream will simply be - * closed when EOF is detected or {@link #close close} is called. - * Otherwise, the watcher decides whether the underlying stream - * should be closed before detaching from it. - * - * @param in the wrapped stream - * @param watcher the watcher for events, or null for - * auto-close behavior without notification - */ - public EofSensorInputStreamHC4(final InputStream in, - final EofSensorWatcher watcher) { - Args.notNull(in, "Wrapped stream"); - wrappedStream = in; - selfClosed = false; - eofWatcher = watcher; - } - - boolean isSelfClosed() { - return selfClosed; - } - - InputStream getWrappedStream() { - return wrappedStream; - } - - /** - * Checks whether the underlying stream can be read from. - * - * @return true if the underlying stream is accessible, - * false if this stream is in EOF mode and - * detached from the underlying stream - * - * @throws IOException if this stream is already closed - */ - protected boolean isReadAllowed() throws IOException { - if (selfClosed) { - throw new IOException("Attempted read on closed stream."); - } - return (wrappedStream != null); - } - - @Override - public int read() throws IOException { - int l = -1; - - if (isReadAllowed()) { - try { - l = wrappedStream.read(); - checkEOF(l); - } catch (final IOException ex) { - checkAbort(); - throw ex; - } - } - - return l; - } - - @Override - public int read(final byte[] b, final int off, final int len) throws IOException { - int l = -1; - - if (isReadAllowed()) { - try { - l = wrappedStream.read(b, off, len); - checkEOF(l); - } catch (final IOException ex) { - checkAbort(); - throw ex; - } - } - - return l; - } - - @Override - public int read(final byte[] b) throws IOException { - return read(b, 0, b.length); - } - - @Override - public int available() throws IOException { - int a = 0; // not -1 - - if (isReadAllowed()) { - try { - a = wrappedStream.available(); - // no checkEOF() here, available() can't trigger EOF - } catch (final IOException ex) { - checkAbort(); - throw ex; - } - } - - return a; - } - - @Override - public void close() throws IOException { - // tolerate multiple calls to close() - selfClosed = true; - checkClose(); - } - - /** - * Detects EOF and notifies the watcher. - * This method should only be called while the underlying stream is - * still accessible. Use {@link #isReadAllowed isReadAllowed} to - * check that condition. - *
    - * If EOF is detected, the watcher will be notified and this stream - * is detached from the underlying stream. This prevents multiple - * notifications from this stream. - * - * @param eof the result of the calling read operation. - * A negative value indicates that EOF is reached. - * - * @throws IOException - * in case of an IO problem on closing the underlying stream - */ - protected void checkEOF(final int eof) throws IOException { - - if ((wrappedStream != null) && (eof < 0)) { - try { - boolean scws = true; // should close wrapped stream? - if (eofWatcher != null) { - scws = eofWatcher.eofDetected(wrappedStream); - } - if (scws) { - wrappedStream.close(); - } - } finally { - wrappedStream = null; - } - } - } - - /** - * Detects stream close and notifies the watcher. - * There's not much to detect since this is called by {@link #close close}. - * The watcher will only be notified if this stream is closed - * for the first time and before EOF has been detected. - * This stream will be detached from the underlying stream to prevent - * multiple notifications to the watcher. - * - * @throws IOException - * in case of an IO problem on closing the underlying stream - */ - protected void checkClose() throws IOException { - - if (wrappedStream != null) { - try { - boolean scws = true; // should close wrapped stream? - if (eofWatcher != null) { - scws = eofWatcher.streamClosed(wrappedStream); - } - if (scws) { - wrappedStream.close(); - } - } finally { - wrappedStream = null; - } - } - } - - /** - * Detects stream abort and notifies the watcher. - * There's not much to detect since this is called by - * {@link #abortConnection abortConnection}. - * The watcher will only be notified if this stream is aborted - * for the first time and before EOF has been detected or the - * stream has been {@link #close closed} gracefully. - * This stream will be detached from the underlying stream to prevent - * multiple notifications to the watcher. - * - * @throws IOException - * in case of an IO problem on closing the underlying stream - */ - protected void checkAbort() throws IOException { - - if (wrappedStream != null) { - try { - boolean scws = true; // should close wrapped stream? - if (eofWatcher != null) { - scws = eofWatcher.streamAbort(wrappedStream); - } - if (scws) { - wrappedStream.close(); - } - } finally { - wrappedStream = null; - } - } - } - - /** - * Same as {@link #close close()}. - */ - public void releaseConnection() throws IOException { - close(); - } - - /** - * Aborts this stream. - * This is a special version of {@link #close close()} which prevents - * re-use of the underlying connection, if any. Calling this method - * indicates that there should be no attempt to read until the end of - * the stream. - */ - public void abortConnection() throws IOException { - // tolerate multiple calls - selfClosed = true; - checkAbort(); - } - -} - diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/HttpClientConnectionManager.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/HttpClientConnectionManager.java deleted file mode 100644 index bbac0b36..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/HttpClientConnectionManager.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.conn; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -import org.apache.http.HttpClientConnection; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.protocol.HttpContext; - -/** - * Represents a manager of persistent client connections. - *

    - * The purpose of an HTTP connection manager is to serve as a factory for new - * HTTP connections, manage persistent connections and synchronize access to - * persistent connections making sure that only one thread of execution can - * have access to a connection at a time. - *

    - * Implementations of this interface must be thread-safe. Access to shared - * data must be synchronized as methods of this interface may be executed - * from multiple threads. - * - * @since 4.3 - */ -public interface HttpClientConnectionManager { - - /** - * Returns a new {@link ConnectionRequest}, from which a - * {@link HttpClientConnection} can be obtained or the request can be - * aborted. - *

    - * Please note that newly allocated connections can be returned - * in the closed state. The consumer of that connection is responsible - * for fully establishing the route the to the connection target - * by calling {@link #connect(org.apache.http.HttpClientConnection, - * org.apache.http.conn.routing.HttpRoute, int, - * org.apache.http.protocol.HttpContext) connect} in order to connect - * directly to the target or to the first proxy hop, optionally calling - * {@link #upgrade(org.apache.http.HttpClientConnection, - * org.apache.http.conn.routing.HttpRoute, - * org.apache.http.protocol.HttpContext) upgrade} method to upgrade - * the connection after having executed CONNECT method to - * all intermediate proxy hops and and finally calling {@link #routeComplete( - * org.apache.http.HttpClientConnection, - * org.apache.http.conn.routing.HttpRoute, - * org.apache.http.protocol.HttpContext) routeComplete} to mark the route - * as fully completed. - * - * @param route HTTP route of the requested connection. - * @param state expected state of the connection or null - * if the connection is not expected to carry any state. - */ - ConnectionRequest requestConnection(HttpRoute route, Object state); - - /** - * Releases the connection back to the manager making it potentially - * re-usable by other consumers. Optionally, the maximum period - * of how long the manager should keep the connection alive can be - * defined using validDuration and timeUnit - * parameters. - * - * @param conn the managed connection to release. - * @param validDuration the duration of time this connection is valid for reuse. - * @param timeUnit the time unit. - * - * @see #closeExpiredConnections() - */ - void releaseConnection( - HttpClientConnection conn, Object newState, long validDuration, TimeUnit timeUnit); - - /** - * Connects the underlying connection socket to the connection target in case - * of a direct route or to the first proxy hop in case of a route via a proxy - * (or multiple proxies). - * - * @param conn the managed connection. - * @param route the route of the connection. - * @param connectTimeout connect timeout in milliseconds. - * @param context the actual HTTP context. - * @throws IOException - */ - void connect( - HttpClientConnection conn, - HttpRoute route, - int connectTimeout, - HttpContext context) throws IOException; - - /** - * Upgrades the underlying connection socket to TLS/SSL (or another layering - * protocol) after having executed CONNECT method to all - * intermediate proxy hops - * - * @param conn the managed connection. - * @param route the route of the connection. - * @param context the actual HTTP context. - * @throws IOException - */ - void upgrade( - HttpClientConnection conn, - HttpRoute route, - HttpContext context) throws IOException; - - /** - * Marks the connection as fully established with all its intermediate - * hops completed. - * - * @param conn the managed connection. - * @param route the route of the connection. - * @param context the actual HTTP context. - * @throws IOException - */ - void routeComplete( - HttpClientConnection conn, - HttpRoute route, - HttpContext context) throws IOException; - - /** - * Closes idle connections in the pool. - *

    - * Open connections in the pool that have not been used for the - * timespan given by the argument will be closed. - * Currently allocated connections are not subject to this method. - * Times will be checked with milliseconds precision - * - * All expired connections will also be closed. - * - * @param idletime the idle time of connections to be closed - * @param tunit the unit for the idletime - * - * @see #closeExpiredConnections() - */ - void closeIdleConnections(long idletime, TimeUnit tunit); - - /** - * Closes all expired connections in the pool. - *

    - * Open connections in the pool that have not been used for - * the timespan defined when the connection was released will be closed. - * Currently allocated connections are not subject to this method. - * Times will be checked with milliseconds precision. - */ - void closeExpiredConnections(); - - /** - * Shuts down this connection manager and releases allocated resources. - * This includes closing all connections, whether they are currently - * used or not. - */ - void shutdown(); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/HttpConnectionFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/HttpConnectionFactory.java deleted file mode 100644 index 746c2ea4..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/HttpConnectionFactory.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.conn; - -import org.apache.http.HttpConnection; -import org.apache.http.config.ConnectionConfig; - -/** - * Generic {@link HttpConnection} factory. - * - * @since 4.3 - */ -public interface HttpConnectionFactory { - - C create(T route, ConnectionConfig config); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/HttpInetSocketAddress.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/HttpInetSocketAddress.java deleted file mode 100644 index 7a6062d2..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/HttpInetSocketAddress.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.conn; - -import java.net.InetAddress; -import java.net.InetSocketAddress; - -import org.apache.http.HttpHost; -import org.apache.http.util.Args; - -/** - * Extended {@link InetSocketAddress} implementation that also provides access to the original - * {@link HttpHost} used to resolve the address. - * - * @since 4.2 no longer used. - * - * @deprecated (4.3) - */ -@Deprecated -public class HttpInetSocketAddress extends InetSocketAddress { - - private static final long serialVersionUID = -6650701828361907957L; - - private final HttpHost httphost; - - public HttpInetSocketAddress(final HttpHost httphost, final InetAddress addr, final int port) { - super(addr, port); - Args.notNull(httphost, "HTTP host"); - this.httphost = httphost; - } - - public HttpHost getHttpHost() { - return this.httphost; - } - - @Override - public String toString() { - return this.httphost.getHostName() + ":" + getPort(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/HttpRoutedConnection.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/HttpRoutedConnection.java deleted file mode 100644 index 416f357b..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/HttpRoutedConnection.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn; - -import javax.net.ssl.SSLSession; - -import org.apache.http.HttpInetConnection; -import org.apache.http.conn.routing.HttpRoute; - -/** - * Interface to access routing information of a client side connection. - * - * @since 4.1 - * - * @deprecated (4.3) replaced by {@link HttpClientConnectionManager}. - */ -@Deprecated -public interface HttpRoutedConnection extends HttpInetConnection { - - /** - * Indicates whether this connection is secure. - * The return value is well-defined only while the connection is open. - * It may change even while the connection is open. - * - * @return true if this connection is secure, - * false otherwise - */ - boolean isSecure(); - - /** - * Obtains the current route of this connection. - * - * @return the route established so far, or - * null if not connected - */ - HttpRoute getRoute(); - - /** - * Obtains the SSL session of the underlying connection, if any. - * If this connection is open, and the underlying socket is an - * {@link javax.net.ssl.SSLSocket SSLSocket}, the SSL session of - * that socket is obtained. This is a potentially blocking operation. - *
    - * Note: Whether the underlying socket is an SSL socket - * can not necessarily be determined via {@link #isSecure}. - * Plain sockets may be considered secure, for example if they are - * connected to a known host in the same network segment. - * On the other hand, SSL sockets may be considered insecure, - * for example depending on the chosen cipher suite. - * - * @return the underlying SSL session if available, - * null otherwise - */ - SSLSession getSSLSession(); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ManagedHttpClientConnection.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ManagedHttpClientConnection.java deleted file mode 100644 index 7a98420a..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ManagedHttpClientConnection.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn; - -import java.io.IOException; -import java.net.Socket; - -import javax.net.ssl.SSLSession; - -import org.apache.http.HttpClientConnection; -import org.apache.http.HttpInetConnection; - -/** - * Represents a managed connection whose state and life cycle is managed by - * a connection manager. This interface extends {@link HttpClientConnection} - * with methods to bind the connection to an arbitrary socket and - * to obtain SSL session details. - * - * @since 4.3 - */ -public interface ManagedHttpClientConnection extends HttpClientConnection, HttpInetConnection { - - /** - * Returns connection ID which is expected to be unique - * for the life span of the connection manager. - */ - String getId(); - - /** - * Binds this connection to the given socket. The connection - * is considered open if it is bound and the underlying socket - * is connection to a remote host. - * - * @param socket the socket to bind the connection to. - * @throws IOException - */ - void bind(Socket socket) throws IOException; - - /** - * Returns the underlying socket. - */ - Socket getSocket(); - - /** - * Obtains the SSL session of the underlying connection, if any. - * If this connection is open, and the underlying socket is an - * {@link javax.net.ssl.SSLSocket SSLSocket}, the SSL session of - * that socket is obtained. This is a potentially blocking operation. - * - * @return the underlying SSL session if available, - * null otherwise - */ - SSLSession getSSLSession(); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/SchemePortResolver.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/SchemePortResolver.java deleted file mode 100644 index 848ad2f7..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/SchemePortResolver.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.conn; - -import org.apache.http.HttpHost; - -/** - * Strategy for default port resolution for protocol schemes. - * - * @since 4.3 - */ -public interface SchemePortResolver { - - /** - * Returns the actual port for the host based on the protocol scheme. - */ - int resolve(HttpHost host) throws UnsupportedSchemeException; - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/UnsupportedSchemeException.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/UnsupportedSchemeException.java deleted file mode 100644 index 268a0b80..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/UnsupportedSchemeException.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn; - -import java.io.IOException; - -import org.apache.http.annotation.Immutable; - -/** - * Signals failure to establish connection using an unknown protocol scheme. - * - * @since 4.3 - */ -@Immutable -public class UnsupportedSchemeException extends IOException { - - private static final long serialVersionUID = 3597127619218687636L; - - /** - * Creates a UnsupportedSchemeException with the specified detail message. - */ - public UnsupportedSchemeException(final String message) { - super(message); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/package-info.java deleted file mode 100644 index 7cbe84cd..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Client connection management APIs. - */ -package org.apache.http.conn; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/params/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/params/package-info.java deleted file mode 100644 index 771190b5..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/params/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Deprecated. - * @deprecated (4.3). - */ -package org.apache.http.conn.params; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/routing/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/routing/package-info.java deleted file mode 100644 index 12ff5b4f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/routing/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Client connection routing APIs. - */ -package org.apache.http.conn.routing; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/LayeredSchemeSocketFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/LayeredSchemeSocketFactory.java deleted file mode 100644 index dedfe502..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/LayeredSchemeSocketFactory.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.Socket; -import java.net.UnknownHostException; - -/** - * Extended {@link SchemeSocketFactory} interface for layered sockets such as SSL/TLS. - * - * @since 4.1 - * - * @deprecated (4.2) use {@link SchemeLayeredSocketFactory} - */ -@Deprecated -public interface LayeredSchemeSocketFactory extends SchemeSocketFactory { - - /** - * Returns a socket connected to the given host that is layered over an - * existing socket. Used primarily for creating secure sockets through - * proxies. - * - * @param socket the existing socket - * @param target the name of the target host. - * @param port the port to connect to on the target host - * @param autoClose a flag for closing the underling socket when the created - * socket is closed - * - * @return Socket a new socket - * - * @throws IOException if an I/O error occurs while creating the socket - * @throws UnknownHostException if the IP address of the host cannot be - * determined - */ - Socket createLayeredSocket( - Socket socket, - String target, - int port, - boolean autoClose - ) throws IOException, UnknownHostException; - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/LayeredSocketFactoryAdaptor.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/LayeredSocketFactoryAdaptor.java deleted file mode 100644 index c836931f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/LayeredSocketFactoryAdaptor.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.Socket; -import java.net.UnknownHostException; - -/** - * @deprecated (4.1) do not use - */ -@Deprecated -class LayeredSocketFactoryAdaptor extends SocketFactoryAdaptor implements LayeredSocketFactory { - - private final LayeredSchemeSocketFactory factory; - - LayeredSocketFactoryAdaptor(final LayeredSchemeSocketFactory factory) { - super(factory); - this.factory = factory; - } - - public Socket createSocket( - final Socket socket, - final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException { - return this.factory.createLayeredSocket(socket, host, port, autoClose); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SchemeLayeredSocketFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SchemeLayeredSocketFactory.java deleted file mode 100644 index cf6c9e6b..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SchemeLayeredSocketFactory.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.Socket; -import java.net.UnknownHostException; - -import org.apache.http.params.HttpParams; - -/** - * Extended {@link SchemeSocketFactory} interface for layered sockets such as SSL/TLS. - * - * @since 4.2 - * - * @deprecated (4.3) use {@link - * org.apache.http.conn.socket.LayeredConnectionSocketFactory} - */ -@Deprecated -public interface SchemeLayeredSocketFactory extends SchemeSocketFactory { - - /** - * Returns a socket connected to the given host that is layered over an - * existing socket. Used primarily for creating secure sockets through - * proxies. - * - * @param socket the existing socket - * @param target the name of the target host. - * @param port the port to connect to on the target host - * @param params HTTP parameters - * - * @return Socket a new socket - * - * @throws IOException if an I/O error occurs while creating the socket - * @throws UnknownHostException if the IP address of the host cannot be - * determined - */ - Socket createLayeredSocket( - Socket socket, - String target, - int port, - HttpParams params) throws IOException, UnknownHostException; - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SchemeLayeredSocketFactoryAdaptor.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SchemeLayeredSocketFactoryAdaptor.java deleted file mode 100644 index c4d5618d..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SchemeLayeredSocketFactoryAdaptor.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.Socket; -import java.net.UnknownHostException; - -import org.apache.http.params.HttpParams; - -/** - * @deprecated (4.2) do not use - */ -@Deprecated -class SchemeLayeredSocketFactoryAdaptor extends SchemeSocketFactoryAdaptor - implements SchemeLayeredSocketFactory { - - private final LayeredSocketFactory factory; - - SchemeLayeredSocketFactoryAdaptor(final LayeredSocketFactory factory) { - super(factory); - this.factory = factory; - } - - public Socket createLayeredSocket( - final Socket socket, - final String target, final int port, - final HttpParams params) throws IOException, UnknownHostException { - return this.factory.createSocket(socket, target, port, true); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SchemeLayeredSocketFactoryAdaptor2.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SchemeLayeredSocketFactoryAdaptor2.java deleted file mode 100644 index 4d10630c..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SchemeLayeredSocketFactoryAdaptor2.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.UnknownHostException; - -import org.apache.http.conn.ConnectTimeoutException; -import org.apache.http.params.HttpParams; - -/** - * @deprecated (4.2) do not use - */ -@Deprecated -class SchemeLayeredSocketFactoryAdaptor2 implements SchemeLayeredSocketFactory { - - private final LayeredSchemeSocketFactory factory; - - SchemeLayeredSocketFactoryAdaptor2(final LayeredSchemeSocketFactory factory) { - super(); - this.factory = factory; - } - - public Socket createSocket(final HttpParams params) throws IOException { - return this.factory.createSocket(params); - } - - public Socket connectSocket( - final Socket sock, - final InetSocketAddress remoteAddress, - final InetSocketAddress localAddress, - final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { - return this.factory.connectSocket(sock, remoteAddress, localAddress, params); - } - - public boolean isSecure(final Socket sock) throws IllegalArgumentException { - return this.factory.isSecure(sock); - } - - public Socket createLayeredSocket( - final Socket socket, - final String target, final int port, - final HttpParams params) throws IOException, UnknownHostException { - return this.factory.createLayeredSocket(socket, target, port, true); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SchemeSocketFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SchemeSocketFactory.java deleted file mode 100644 index f2f1a754..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SchemeSocketFactory.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.UnknownHostException; - -import org.apache.http.conn.ConnectTimeoutException; -import org.apache.http.params.HttpParams; - -/** - * A factory for creating, initializing and connecting sockets. The factory encapsulates the logic - * for establishing a socket connection. - * - * @since 4.1 - * - * @deprecated (4.3) use {@link org.apache.http.conn.socket.ConnectionSocketFactory} - */ -@Deprecated -public interface SchemeSocketFactory { - - /** - * Creates a new, unconnected socket. The socket should subsequently be passed to - * {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams)}. - * - * @param params Optional {@link HttpParams parameters}. In most cases these parameters - * will not be required and will have no effect, as usually socket - * initialization should take place in the - * {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams)} - * method. However, in rare cases one may want to pass additional parameters - * to this method in order to create a customized {@link Socket} instance, - * for instance bound to a SOCKS proxy server. - * - * @return a new socket - * - * @throws IOException if an I/O error occurs while creating the socket - */ - Socket createSocket(HttpParams params) throws IOException; - - /** - * Connects a socket to the target host with the given remote address. - *

    - * Please note that {@link org.apache.http.conn.HttpInetSocketAddress} class should - * be used in order to pass the target remote address along with the original - * {@link org.apache.http.HttpHost} value used to resolve the address. The use of - * {@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 - * {@link #createSocket(HttpParams) createSocket}. - * null indicates that a new socket - * should be created and connected. - * @param remoteAddress the remote address to connect to. - * @param localAddress the local address to bind the socket to, or - * null for any - * @param params additional {@link HttpParams parameters} for connecting - * - * @return the connected socket. The returned object may be different - * from the sock argument if this factory supports - * a layered protocol. - * - * @throws IOException if an I/O error occurs - * @throws UnknownHostException if the IP address of the target host - * can not be determined - * @throws ConnectTimeoutException if the socket cannot be connected - * within the time limit defined in the params - * - * @see org.apache.http.conn.HttpInetSocketAddress - */ - Socket connectSocket( - Socket sock, - InetSocketAddress remoteAddress, - InetSocketAddress localAddress, - HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException; - - /** - * Checks whether a socket provides a secure connection. The socket must be - * {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams) connected} - * by this factory. The factory will not perform I/O operations in this method. - *

    - * As a rule of thumb, plain sockets are not secure and TLS/SSL sockets are secure. However, - * there may be application specific deviations. For example, a plain socket to a host in the - * same intranet ("trusted zone") could be considered secure. On the other hand, a TLS/SSL - * socket could be considered insecure based on the cipher suite chosen for the connection. - * - * @param sock the connected socket to check - * - * @return true if the connection of the socket - * should be considered secure, or - * false if it should not - * - * @throws IllegalArgumentException - * if the argument is invalid, for example because it is - * not a connected socket or was created by a different - * socket factory. - * Note that socket factories are not required to - * check these conditions, they may simply return a default - * value when called with an invalid socket argument. - */ - boolean isSecure(Socket sock) throws IllegalArgumentException; - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SchemeSocketFactoryAdaptor.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SchemeSocketFactoryAdaptor.java deleted file mode 100644 index 70023a67..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SchemeSocketFactoryAdaptor.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.UnknownHostException; - -import org.apache.http.conn.ConnectTimeoutException; -import org.apache.http.params.HttpParams; - -/** - * @deprecated (4.1) do not use - */ -@Deprecated -class SchemeSocketFactoryAdaptor implements SchemeSocketFactory { - - private final SocketFactory factory; - - SchemeSocketFactoryAdaptor(final SocketFactory factory) { - super(); - this.factory = factory; - } - - public Socket connectSocket( - final Socket sock, - final InetSocketAddress remoteAddress, - final InetSocketAddress localAddress, - final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { - final String host = remoteAddress.getHostName(); - final int port = remoteAddress.getPort(); - InetAddress local = null; - int localPort = 0; - if (localAddress != null) { - local = localAddress.getAddress(); - localPort = localAddress.getPort(); - } - return this.factory.connectSocket(sock, host, port, local, localPort, params); - } - - public Socket createSocket(final HttpParams params) throws IOException { - return this.factory.createSocket(); - } - - public boolean isSecure(final Socket sock) throws IllegalArgumentException { - return this.factory.isSecure(sock); - } - - public SocketFactory getFactory() { - return this.factory; - } - - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - if (obj instanceof SchemeSocketFactoryAdaptor) { - return this.factory.equals(((SchemeSocketFactoryAdaptor)obj).factory); - } else { - return this.factory.equals(obj); - } - } - - @Override - public int hashCode() { - return this.factory.hashCode(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SocketFactoryAdaptor.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SocketFactoryAdaptor.java deleted file mode 100644 index 8e4a5cc2..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/SocketFactoryAdaptor.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.scheme; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.UnknownHostException; - -import org.apache.http.conn.ConnectTimeoutException; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpParams; - -@Deprecated -class SocketFactoryAdaptor implements SocketFactory { - - private final SchemeSocketFactory factory; - - SocketFactoryAdaptor(final SchemeSocketFactory factory) { - super(); - this.factory = factory; - } - - public Socket createSocket() throws IOException { - final HttpParams params = new BasicHttpParams(); - return this.factory.createSocket(params); - } - - public Socket connectSocket( - final Socket socket, - final String host, final int port, - final InetAddress localAddress, final int localPort, - final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { - InetSocketAddress local = null; - if (localAddress != null || localPort > 0) { - local = new InetSocketAddress(localAddress, localPort > 0 ? localPort : 0); - } - final InetAddress remoteAddress = InetAddress.getByName(host); - final InetSocketAddress remote = new InetSocketAddress(remoteAddress, port); - return this.factory.connectSocket(socket, remote, local, params); - } - - public boolean isSecure(final Socket socket) throws IllegalArgumentException { - return this.factory.isSecure(socket); - } - - public SchemeSocketFactory getFactory() { - return this.factory; - } - - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - if (obj instanceof SocketFactoryAdaptor) { - return this.factory.equals(((SocketFactoryAdaptor)obj).factory); - } else { - return this.factory.equals(obj); - } - } - - @Override - public int hashCode() { - return this.factory.hashCode(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/package-info.java deleted file mode 100644 index 56197708..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/scheme/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Deprecated. - * @deprecated (4.3). - */ -package org.apache.http.conn.scheme; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/socket/ConnectionSocketFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/socket/ConnectionSocketFactory.java deleted file mode 100644 index 29ee7b47..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/socket/ConnectionSocketFactory.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.socket; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; - -import org.apache.http.HttpHost; -import org.apache.http.protocol.HttpContext; - -/** - * A factory for creating and connecting connection sockets. - * - * @since 4.3 - */ -public interface ConnectionSocketFactory { - - /** - * Creates new, unconnected socket. The socket should subsequently be passed to - * {@link #connectSocket(int, Socket, HttpHost, InetSocketAddress, InetSocketAddress, - * HttpContext) connectSocket} method. - * - * @return a new socket - * - * @throws IOException if an I/O error occurs while creating the socket - */ - Socket createSocket(HttpContext context) throws IOException; - - /** - * Connects the socket to the target host with the given resolved remote address. - * - * @param connectTimeout connect timeout. - * @param sock the socket to connect, as obtained from {@link #createSocket(HttpContext)}. - * null indicates that a new socket should be created and connected. - * @param host target host as specified by the caller (end user). - * @param remoteAddress the resolved remote address to connect to. - * @param localAddress the local address to bind the socket to, or null for any. - * @param context the actual HTTP context. - * - * @return the connected socket. The returned object may be different - * from the sock argument if this factory supports - * a layered protocol. - * - * @throws IOException if an I/O error occurs - */ - Socket connectSocket( - int connectTimeout, - Socket sock, - HttpHost host, - InetSocketAddress remoteAddress, - InetSocketAddress localAddress, - HttpContext context) throws IOException; - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/socket/LayeredConnectionSocketFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/socket/LayeredConnectionSocketFactory.java deleted file mode 100644 index 3f4e2a9a..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/socket/LayeredConnectionSocketFactory.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.socket; - -import java.io.IOException; -import java.net.Socket; -import java.net.UnknownHostException; - -import org.apache.http.protocol.HttpContext; - -/** - * Extended {@link ConnectionSocketFactory} interface for layered sockets such as SSL/TLS. - * - * @since 4.3 - */ -public interface LayeredConnectionSocketFactory extends ConnectionSocketFactory { - - /** - * Returns a socket connected to the given host that is layered over an - * existing socket. Used primarily for creating secure sockets through - * proxies. - * - * @param socket the existing socket - * @param target the name of the target host. - * @param port the port to connect to on the target host. - * @param context the actual HTTP context. - * - * @return Socket a new socket - * - * @throws IOException if an I/O error occurs while creating the socket - */ - Socket createLayeredSocket( - Socket socket, - String target, - int port, - HttpContext context) throws IOException, UnknownHostException; - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/socket/PlainConnectionSocketFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/socket/PlainConnectionSocketFactory.java deleted file mode 100644 index 0d373f40..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/socket/PlainConnectionSocketFactory.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.socket; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; - -import org.apache.http.HttpHost; -import org.apache.http.annotation.Immutable; -import org.apache.http.protocol.HttpContext; - -/** - * The default class for creating plain (unencrypted) sockets. - * - * @since 4.3 - */ -@Immutable -public class PlainConnectionSocketFactory implements ConnectionSocketFactory { - - public static final PlainConnectionSocketFactory INSTANCE = new PlainConnectionSocketFactory(); - - public static PlainConnectionSocketFactory getSocketFactory() { - return INSTANCE; - } - - public PlainConnectionSocketFactory() { - super(); - } - - public Socket createSocket(final HttpContext context) throws IOException { - return new Socket(); - } - - public Socket connectSocket( - final int connectTimeout, - final Socket socket, - final HttpHost host, - final InetSocketAddress remoteAddress, - final InetSocketAddress localAddress, - final HttpContext context) throws IOException { - final Socket sock = socket != null ? socket : createSocket(context); - if (localAddress != null) { - sock.bind(localAddress); - } - try { - sock.connect(remoteAddress, connectTimeout); - } catch (final IOException ex) { - try { - sock.close(); - } catch (final IOException ignore) { - } - throw ex; - } - return sock; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/socket/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/socket/package-info.java deleted file mode 100644 index aeb46f54..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/socket/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Client connection socket APIs. - */ -package org.apache.http.conn.socket; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/AbstractVerifierHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/AbstractVerifierHC4.java deleted file mode 100644 index d122c5e3..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/AbstractVerifierHC4.java +++ /dev/null @@ -1,384 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.ssl; - -import java.io.IOException; -import java.io.InputStream; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.security.cert.Certificate; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; - -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; -import javax.security.auth.x500.X500Principal; - -import android.util.Log; - -import org.apache.http.NameValuePair; -import org.apache.http.annotation.Immutable; -import org.apache.http.conn.util.InetAddressUtilsHC4; -import org.apache.http.util.TextUtils; - -/** - * Abstract base class for all standard {@link X509HostnameVerifier} - * implementations. - * - * @since 4.0 - */ -@Immutable -public abstract class AbstractVerifierHC4 implements X509HostnameVerifier { - - /** - * This contains a list of 2nd-level domains that aren't allowed to - * have wildcards when combined with country-codes. - * For example: [*.co.uk]. - *

    - * The [*.co.uk] problem is an interesting one. Should we just hope - * that CA's would never foolishly allow such a certificate to happen? - * Looks like we're the only implementation guarding against this. - * Firefox, Curl, Sun Java 1.4, 5, 6 don't bother with this check. - */ - private final static String[] BAD_COUNTRY_2LDS = - { "ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info", - "lg", "ne", "net", "or", "org" }; - - static { - // Just in case developer forgot to manually sort the array. :-) - Arrays.sort(BAD_COUNTRY_2LDS); - } - - private final static String TAG = "HttpClient"; - - public AbstractVerifierHC4() { - super(); - } - - public final void verify(final String host, final SSLSocket ssl) - throws IOException { - if(host == null) { - throw new NullPointerException("host to verify is null"); - } - - SSLSession session = ssl.getSession(); - if(session == null) { - // In our experience this only happens under IBM 1.4.x when - // spurious (unrelated) certificates show up in the server' - // chain. Hopefully this will unearth the real problem: - final InputStream in = ssl.getInputStream(); - in.available(); - /* - If you're looking at the 2 lines of code above because - you're running into a problem, you probably have two - options: - - #1. Clean up the certificate chain that your server - is presenting (e.g. edit "/etc/apache2/server.crt" - or wherever it is your server's certificate chain - is defined). - - OR - - #2. Upgrade to an IBM 1.5.x or greater JVM, or switch - to a non-IBM JVM. - */ - - // If ssl.getInputStream().available() didn't cause an - // exception, maybe at least now the session is available? - session = ssl.getSession(); - if(session == null) { - // If it's still null, probably a startHandshake() will - // unearth the real problem. - ssl.startHandshake(); - - // Okay, if we still haven't managed to cause an exception, - // might as well go for the NPE. Or maybe we're okay now? - session = ssl.getSession(); - } - } - - final Certificate[] certs = session.getPeerCertificates(); - final X509Certificate x509 = (X509Certificate) certs[0]; - verify(host, x509); - } - - public final boolean verify(final String host, final SSLSession session) { - try { - final Certificate[] certs = session.getPeerCertificates(); - final X509Certificate x509 = (X509Certificate) certs[0]; - verify(host, x509); - return true; - } - catch(final SSLException e) { - return false; - } - } - - public final void verify(final String host, final X509Certificate cert) - throws SSLException { - final String[] cns = getCNs(cert); - final String[] subjectAlts = getSubjectAlts(cert, host); - verify(host, cns, subjectAlts); - } - - public final void verify(final String host, final String[] cns, - final String[] subjectAlts, - final boolean strictWithSubDomains) - throws SSLException { - - // Build the list of names we're going to check. Our DEFAULT and - // STRICT implementations of the HostnameVerifier only use the - // first CN provided. All other CNs are ignored. - // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way). - final LinkedList names = new LinkedList(); - if(cns != null && cns.length > 0 && cns[0] != null) { - names.add(cns[0]); - } - if(subjectAlts != null) { - for (final String subjectAlt : subjectAlts) { - if (subjectAlt != null) { - names.add(subjectAlt); - } - } - } - - if(names.isEmpty()) { - final String msg = "Certificate for <" + host + "> doesn't contain CN or DNS subjectAlt"; - throw new SSLException(msg); - } - - // StringBuilder for building the error message. - final StringBuilder buf = new StringBuilder(); - - // We're can be case-insensitive when comparing the host we used to - // establish the socket to the hostname in the certificate. - final String hostName = normaliseIPv6Address(host.trim().toLowerCase(Locale.ENGLISH)); - boolean match = false; - for(final Iterator it = names.iterator(); it.hasNext();) { - // Don't trim the CN, though! - String cn = it.next(); - cn = cn.toLowerCase(Locale.ENGLISH); - // Store CN in StringBuilder in case we need to report an error. - buf.append(" <"); - buf.append(cn); - buf.append('>'); - if(it.hasNext()) { - buf.append(" OR"); - } - - // The CN better have at least two dots if it wants wildcard - // action. It also can't be [*.co.uk] or [*.co.jp] or - // [*.org.uk], etc... - final String parts[] = cn.split("\\."); - final boolean doWildcard = - parts.length >= 3 && parts[0].endsWith("*") && - validCountryWildcard(cn) && !isIPAddress(host); - - if(doWildcard) { - final String firstpart = parts[0]; - if (firstpart.length() > 1) { // e.g. server* - final String prefix = firstpart.substring(0, firstpart.length() - 1); // e.g. server - final String suffix = cn.substring(firstpart.length()); // skip wildcard part from cn - final String hostSuffix = hostName.substring(prefix.length()); // skip wildcard part from host - match = hostName.startsWith(prefix) && hostSuffix.endsWith(suffix); - } else { - match = hostName.endsWith(cn.substring(1)); - } - if(match && strictWithSubDomains) { - // If we're in strict mode, then [*.foo.com] is not - // allowed to match [a.b.foo.com] - match = countDots(hostName) == countDots(cn); - } - } else { - match = hostName.equals(normaliseIPv6Address(cn)); - } - if(match) { - break; - } - } - if(!match) { - throw new SSLException("hostname in certificate didn't match: <" + host + "> !=" + buf); - } - } - - /** - * @deprecated (4.3.1) should not be a part of public APIs. - */ - @Deprecated - public static boolean acceptableCountryWildcard(final String cn) { - final String parts[] = cn.split("\\."); - if (parts.length != 3 || parts[2].length() != 2) { - return true; // it's not an attempt to wildcard a 2TLD within a country code - } - return Arrays.binarySearch(BAD_COUNTRY_2LDS, parts[1]) < 0; - } - - boolean validCountryWildcard(final String cn) { - final String parts[] = cn.split("\\."); - if (parts.length != 3 || parts[2].length() != 2) { - return true; // it's not an attempt to wildcard a 2TLD within a country code - } - return Arrays.binarySearch(BAD_COUNTRY_2LDS, parts[1]) < 0; - } - - public static String[] getCNs(final X509Certificate cert) { - final String subjectPrincipal = cert.getSubjectX500Principal().toString(); - try { - return extractCNs(subjectPrincipal); - } catch (SSLException ex) { - return null; - } - } - - static String[] extractCNs(final String subjectPrincipal) throws SSLException { - if (subjectPrincipal == null) { - return null; - } - final List cns = new ArrayList(); - final List nvps = DistinguishedNameParser.INSTANCE.parse(subjectPrincipal); - for (int i = 0; i < nvps.size(); i++) { - final NameValuePair nvp = nvps.get(i); - final String attribName = nvp.getName(); - final String attribValue = nvp.getValue(); - if (TextUtils.isBlank(attribName)) { - throw new SSLException(subjectPrincipal + " is not a valid X500 distinguished name"); - } - if (attribName.equalsIgnoreCase("cn")) { - cns.add(attribValue); - } - } - return cns.isEmpty() ? null : cns.toArray(new String[ cns.size() ]); - } - - /** - * Extracts the array of SubjectAlt DNS or IP names from an X509Certificate. - * Returns null if there aren't any. - * - * @param cert X509Certificate - * @param hostname - * @return Array of SubjectALT DNS or IP names stored in the certificate. - */ - private static String[] getSubjectAlts( - final X509Certificate cert, final String hostname) { - final int subjectType; - if (isIPAddress(hostname)) { - subjectType = 7; - } else { - subjectType = 2; - } - - final LinkedList subjectAltList = new LinkedList(); - Collection> c = null; - try { - c = cert.getSubjectAlternativeNames(); - } - catch(final CertificateParsingException cpe) { - } - if(c != null) { - for (final List aC : c) { - final List list = aC; - final int type = ((Integer) list.get(0)).intValue(); - if (type == subjectType) { - final String s = (String) list.get(1); - subjectAltList.add(s); - } - } - } - if(!subjectAltList.isEmpty()) { - final String[] subjectAlts = new String[subjectAltList.size()]; - subjectAltList.toArray(subjectAlts); - return subjectAlts; - } else { - return null; - } - } - - /** - * Extracts the array of SubjectAlt DNS names from an X509Certificate. - * Returns null if there aren't any. - *

    - * Note: Java doesn't appear able to extract international characters - * from the SubjectAlts. It can only extract international characters - * from the CN field. - *

    - * (Or maybe the version of OpenSSL I'm using to test isn't storing the - * international characters correctly in the SubjectAlts?). - * - * @param cert X509Certificate - * @return Array of SubjectALT DNS names stored in the certificate. - */ - public static String[] getDNSSubjectAlts(final X509Certificate cert) { - return getSubjectAlts(cert, null); - } - - /** - * Counts the number of dots "." in a string. - * @param s string to count dots from - * @return number of dots - */ - public static int countDots(final String s) { - int count = 0; - for(int i = 0; i < s.length(); i++) { - if(s.charAt(i) == '.') { - count++; - } - } - return count; - } - - private static boolean isIPAddress(final String hostname) { - return hostname != null && - (InetAddressUtilsHC4.isIPv4Address(hostname) || - InetAddressUtilsHC4.isIPv6Address(hostname)); - } - - /* - * Check if hostname is IPv6, and if so, convert to standard format. - */ - private String normaliseIPv6Address(final String hostname) { - if (hostname == null || !InetAddressUtilsHC4.isIPv6Address(hostname)) { - return hostname; - } - try { - final InetAddress inetAddress = InetAddress.getByName(hostname); - return inetAddress.getHostAddress(); - } catch (final UnknownHostException uhe) { // Should not happen, because we check for IPv6 address above - Log.e(TAG, "Unexpected error converting "+hostname, uhe); - return hostname; - } - } -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/AllowAllHostnameVerifierHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/AllowAllHostnameVerifierHC4.java deleted file mode 100644 index 6f8b49ca..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/AllowAllHostnameVerifierHC4.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.ssl; - -import org.apache.http.annotation.Immutable; - -/** - * The ALLOW_ALL HostnameVerifier essentially turns hostname verification - * off. This implementation is a no-op, and never throws the SSLException. - * - * - * @since 4.0 - */ -@Immutable -public class AllowAllHostnameVerifierHC4 extends AbstractVerifierHC4 { - - public final void verify( - final String host, - final String[] cns, - final String[] subjectAlts) { - // Allow everything - so never blowup. - } - - @Override - public final String toString() { - return "ALLOW_ALL"; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/BrowserCompatHostnameVerifierHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/BrowserCompatHostnameVerifierHC4.java deleted file mode 100644 index 25b6cd28..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/BrowserCompatHostnameVerifierHC4.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.ssl; - -import javax.net.ssl.SSLException; - -import org.apache.http.annotation.Immutable; - -/** - * The HostnameVerifier that works the same way as Curl and Firefox. - *

    - * The hostname must match either the first CN, or any of the subject-alts. - * A wildcard can occur in the CN, and in any of the subject-alts. - *

    - * The only difference between BROWSER_COMPATIBLE and STRICT is that a wildcard - * (such as "*.foo.com") with BROWSER_COMPATIBLE matches all subdomains, - * including "a.b.foo.com". - * - * - * @since 4.0 - */ -@Immutable -public class BrowserCompatHostnameVerifierHC4 extends AbstractVerifierHC4 { - - public final void verify( - final String host, - final String[] cns, - final String[] subjectAlts) throws SSLException { - verify(host, cns, subjectAlts, false); - } - - @Override - boolean validCountryWildcard(final String cn) { - return true; - } - - @Override - public final String toString() { - return "BROWSER_COMPATIBLE"; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/DistinguishedNameParser.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/DistinguishedNameParser.java deleted file mode 100644 index 44362557..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/DistinguishedNameParser.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.ssl; - -import java.util.ArrayList; -import java.util.BitSet; -import java.util.List; - -import org.apache.http.NameValuePair; -import org.apache.http.annotation.Immutable; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.message.ParserCursor; -import org.apache.http.util.CharArrayBuffer; - -@Immutable -final class DistinguishedNameParser { - - public final static DistinguishedNameParser INSTANCE = new DistinguishedNameParser(); - - private static final BitSet EQUAL_OR_COMMA_OR_PLUS = TokenParser.INIT_BITSET('=', ',', '+'); - private static final BitSet COMMA_OR_PLUS = TokenParser.INIT_BITSET(',', '+'); - - private final TokenParser tokenParser; - - DistinguishedNameParser() { - this.tokenParser = new InternalTokenParser(); - } - - String parseToken(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters) { - return tokenParser.parseToken(buf, cursor, delimiters); - } - - String parseValue(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters) { - return tokenParser.parseValue(buf, cursor, delimiters); - } - - NameValuePair parseParameter(final CharArrayBuffer buf, final ParserCursor cursor) { - final String name = parseToken(buf, cursor, EQUAL_OR_COMMA_OR_PLUS); - if (cursor.atEnd()) { - return new BasicNameValuePair(name, null); - } - final int delim = buf.charAt(cursor.getPos()); - cursor.updatePos(cursor.getPos() + 1); - if (delim == ',') { - return new BasicNameValuePair(name, null); - } - final String value = parseValue(buf, cursor, COMMA_OR_PLUS); - if (!cursor.atEnd()) { - cursor.updatePos(cursor.getPos() + 1); - } - return new BasicNameValuePair(name, value); - } - - public List parse(final CharArrayBuffer buf, final ParserCursor cursor) { - final List params = new ArrayList(); - tokenParser.skipWhiteSpace(buf, cursor); - while (!cursor.atEnd()) { - final NameValuePair param = parseParameter(buf, cursor); - params.add(param); - } - return params; - } - - public List parse(final String s) { - if (s == null) { - return null; - } - final CharArrayBuffer buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - final ParserCursor cursor = new ParserCursor(0, s.length()); - return parse(buffer, cursor); - } - - static class InternalTokenParser extends TokenParser { - - @Override - public void copyUnquotedContent( - final CharArrayBuffer buf, - final ParserCursor cursor, - final BitSet delimiters, - final StringBuilder dst) { - int pos = cursor.getPos(); - final int indexFrom = cursor.getPos(); - final int indexTo = cursor.getUpperBound(); - boolean escaped = false; - for (int i = indexFrom; i < indexTo; i++, pos++) { - final char current = buf.charAt(i); - if (escaped) { - dst.append(current); - escaped = false; - } else { - if ((delimiters != null && delimiters.get(current)) - || TokenParser.isWhitespace(current) || current == '\"') { - break; - } else if (current == '\\') { - escaped = true; - } else { - dst.append(current); - } - } - } - cursor.updatePos(pos); - } - } - -} - diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/PrivateKeyDetails.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/PrivateKeyDetails.java deleted file mode 100644 index 1abb449f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/PrivateKeyDetails.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.conn.ssl; - -import org.apache.http.util.Args; - -import java.security.cert.X509Certificate; -import java.util.Arrays; - -/** - * Private key details. - * - * @since 4.3 - */ -public final class PrivateKeyDetails { - - private final String type; - private final X509Certificate[] certChain; - - public PrivateKeyDetails(final String type, final X509Certificate[] certChain) { - super(); - this.type = Args.notNull(type, "Private key type"); - this.certChain = certChain; - } - - public String getType() { - return type; - } - - public X509Certificate[] getCertChain() { - return certChain; - } - - @Override - public String toString() { - return type + ':' + Arrays.toString(certChain); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/PrivateKeyStrategy.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/PrivateKeyStrategy.java deleted file mode 100644 index 4238e287..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/PrivateKeyStrategy.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.conn.ssl; - -import java.net.Socket; -import java.util.Map; - -/** - * A strategy allowing for a choice of an alias during SSL authentication. - * - * @since 4.3 - */ -public interface PrivateKeyStrategy { - - /** - * Determines what key material to use for SSL authentication. - */ - String chooseAlias(Map aliases, Socket socket); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/SSLConnectionSocketFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/SSLConnectionSocketFactory.java deleted file mode 100644 index 7449046a..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/SSLConnectionSocketFactory.java +++ /dev/null @@ -1,399 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.ssl; - -import android.annotation.TargetApi; -import android.os.Build; -import android.util.Log; - -import org.apache.http.HttpHost; -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.conn.socket.LayeredConnectionSocketFactory; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; -import org.apache.http.util.TextUtils; - -import javax.net.SocketFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; -import javax.security.auth.x500.X500Principal; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -/** - * Layered socket factory for TLS/SSL connections. - *

    - * SSLSocketFactory can be used to validate the identity of the HTTPS server against a list of - * trusted certificates and to authenticate to the HTTPS server using a private key. - *

    - * SSLSocketFactory will enable server authentication when supplied with - * a {@link java.security.KeyStore trust-store} file containing one or several trusted certificates. The client - * secure socket will reject the connection during the SSL session handshake if the target HTTPS - * server attempts to authenticate itself with a non-trusted certificate. - *

    - * Use JDK keytool utility to import a trusted certificate and generate a trust-store file: - *

    - *     keytool -import -alias "my server cert" -file server.crt -keystore my.truststore
    - *    
    - *

    - * In special cases the standard trust verification process can be bypassed by using a custom - * {@link org.apache.http.conn.ssl.TrustStrategy}. This interface is primarily intended for allowing self-signed - * certificates to be accepted as trusted without having to add them to the trust-store file. - *

    - * SSLSocketFactory will enable client authentication when supplied with - * a {@link java.security.KeyStore key-store} file containing a private key/public certificate - * pair. The client secure socket will use the private key to authenticate - * itself to the target HTTPS server during the SSL session handshake if - * requested to do so by the server. - * The target HTTPS server will in its turn verify the certificate presented - * by the client in order to establish client's authenticity. - *

    - * Use the following sequence of actions to generate a key-store file - *

    - *
      - *
    • - *

      - * Use JDK keytool utility to generate a new key - *

      keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore
      - * For simplicity use the same password for the key as that of the key-store - *

      - *
    • - *
    • - *

      - * Issue a certificate signing request (CSR) - *

      keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore
      - *

      - *
    • - *
    • - *

      - * Send the certificate request to the trusted Certificate Authority for signature. - * One may choose to act as her own CA and sign the certificate request using a PKI - * tool, such as OpenSSL. - *

      - *
    • - *
    • - *

      - * Import the trusted CA root certificate - *

      keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore
      - *

      - *
    • - *
    • - *

      - * Import the PKCS#7 file containg the complete certificate chain - *

      keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore
      - *

      - *
    • - *
    • - *

      - * Verify the content the resultant keystore file - *

      keytool -list -v -keystore my.keystore
      - *

      - *
    • - *
    - * - * @since 4.0 - */ -@ThreadSafe -public class SSLConnectionSocketFactory implements LayeredConnectionSocketFactory { - - private final static String TAG = "HttpClient"; - - public static final String TLS = "TLS"; - public static final String SSL = "SSL"; - public static final String SSLV2 = "SSLv2"; - - public static final X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER - = new AllowAllHostnameVerifierHC4(); - - public static final X509HostnameVerifier BROWSER_COMPATIBLE_HOSTNAME_VERIFIER - = new BrowserCompatHostnameVerifierHC4(); - - public static final X509HostnameVerifier STRICT_HOSTNAME_VERIFIER - = new StrictHostnameVerifierHC4(); - - /** - * Obtains default SSL socket factory with an SSL context based on the standard JSSE - * trust material (cacerts file in the security properties directory). - * System properties are not taken into consideration. - * - * @return default SSL socket factory - */ - public static SSLConnectionSocketFactory getSocketFactory() throws SSLInitializationException { - return new SSLConnectionSocketFactory( - (javax.net.ssl.SSLSocketFactory) SSLSocketFactory.getDefault(), - BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); - } - - private static String[] split(final String s) { - if (TextUtils.isBlank(s)) { - return null; - } - return s.split(" *, *"); - } - - /** - * Obtains default SSL socket factory with an SSL context based on system properties - * as described in - * - * "JavaTM Secure Socket Extension (JSSE) Reference Guide for the JavaTM 2 Platform - * Standard Edition 5 - * - * @return default system SSL socket factory - */ - public static SSLConnectionSocketFactory getSystemSocketFactory() throws SSLInitializationException { - return new SSLConnectionSocketFactory( - (javax.net.ssl.SSLSocketFactory) SSLSocketFactory.getDefault(), - split(System.getProperty("https.protocols")), - split(System.getProperty("https.cipherSuites")), - BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); - } - - private final javax.net.ssl.SSLSocketFactory socketfactory; - private final X509HostnameVerifier hostnameVerifier; - private final String[] supportedProtocols; - private final String[] supportedCipherSuites; - - public SSLConnectionSocketFactory(final SSLContext sslContext) { - this(sslContext, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); - } - - public SSLConnectionSocketFactory( - final SSLContext sslContext, final X509HostnameVerifier hostnameVerifier) { - this(Args.notNull(sslContext, "SSL context").getSocketFactory(), - null, null, hostnameVerifier); - } - - public SSLConnectionSocketFactory( - final SSLContext sslContext, - final String[] supportedProtocols, - final String[] supportedCipherSuites, - final X509HostnameVerifier hostnameVerifier) { - this(Args.notNull(sslContext, "SSL context").getSocketFactory(), - supportedProtocols, supportedCipherSuites, hostnameVerifier); - } - - public SSLConnectionSocketFactory( - final javax.net.ssl.SSLSocketFactory socketfactory, - final X509HostnameVerifier hostnameVerifier) { - this(socketfactory, null, null, hostnameVerifier); - } - - public SSLConnectionSocketFactory( - final javax.net.ssl.SSLSocketFactory socketfactory, - final String[] supportedProtocols, - final String[] supportedCipherSuites, - final X509HostnameVerifier hostnameVerifier) { - this.socketfactory = Args.notNull(socketfactory, "SSL socket factory"); - this.supportedProtocols = supportedProtocols; - this.supportedCipherSuites = supportedCipherSuites; - this.hostnameVerifier = hostnameVerifier != null ? hostnameVerifier : BROWSER_COMPATIBLE_HOSTNAME_VERIFIER; - } - - /** - * Performs any custom initialization for a newly created SSLSocket - * (before the SSL handshake happens). - * - * The default implementation is a no-op, but could be overridden to, e.g., - * call {@link javax.net.ssl.SSLSocket#setEnabledCipherSuites(String[])}. - */ - protected void prepareSocket(final SSLSocket socket) throws IOException { - } - - public Socket createSocket(final HttpContext context) throws IOException { - return SocketFactory.getDefault().createSocket(); - } - - public Socket connectSocket( - final int connectTimeout, - final Socket socket, - final HttpHost host, - final InetSocketAddress remoteAddress, - final InetSocketAddress localAddress, - final HttpContext context) throws IOException { - Args.notNull(host, "HTTP host"); - Args.notNull(remoteAddress, "Remote address"); - final Socket sock = socket != null ? socket : createSocket(context); - if (localAddress != null) { - sock.bind(localAddress); - } - try { - if (connectTimeout > 0 && sock.getSoTimeout() == 0) { - sock.setSoTimeout(connectTimeout); - } - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Connecting socket to " + remoteAddress + " with timeout " + connectTimeout); - } - sock.connect(remoteAddress, connectTimeout); - } catch (final IOException ex) { - try { - sock.close(); - } catch (final IOException ignore) { - } - throw ex; - } - // Setup SSL layering if necessary - if (sock instanceof SSLSocket) { - final SSLSocket sslsock = (SSLSocket) sock; - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Starting handshake"); - } - sslsock.startHandshake(); - verifyHostname(sslsock, host.getHostName()); - return sock; - } else { - return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context); - } - } - - @TargetApi(9) - public Socket createLayeredSocket( - final Socket socket, - final String target, - final int port, - final HttpContext context) throws IOException { - final SSLSocket sslsock = (SSLSocket) this.socketfactory.createSocket( - socket, - target, - port, - true); - if (supportedProtocols != null) { - sslsock.setEnabledProtocols(supportedProtocols); - } else { - // If supported protocols are not explicitly set, remove all SSL protocol versions - final String[] allProtocols = sslsock.getEnabledProtocols(); - final List enabledProtocols = new ArrayList(allProtocols.length); - for (String protocol: allProtocols) { - if (!protocol.startsWith("SSL")) { - enabledProtocols.add(protocol); - } - } - if (!enabledProtocols.isEmpty()) { - sslsock.setEnabledProtocols(enabledProtocols.toArray(new String[enabledProtocols.size()])); - } - } - if (supportedCipherSuites != null) { - sslsock.setEnabledCipherSuites(supportedCipherSuites); - } - - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Enabled protocols: " + Arrays.asList(sslsock.getEnabledProtocols())); - Log.d(TAG, "Enabled cipher suites:" + Arrays.asList(sslsock.getEnabledCipherSuites())); - } - prepareSocket(sslsock); - - // Android specific code to enable SNI - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Enabling SNI for " + target); - } - try { - Method method = sslsock.getClass().getMethod("setHostname", String.class); - method.invoke(sslsock, target); - } catch (Exception ex) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "SNI configuration failed", ex); - } - } - } - // End of Android specific code - - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Starting handshake"); - } - sslsock.startHandshake(); - verifyHostname(sslsock, target); - return sslsock; - } - - X509HostnameVerifier getHostnameVerifier() { - return this.hostnameVerifier; - } - - private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException { - try { - if (Log.isLoggable(TAG, Log.DEBUG)) { - try { - final SSLSession session = sslsock.getSession(); - Log.d(TAG, "Secure session established"); - Log.d(TAG, " negotiated protocol: " + session.getProtocol()); - Log.d(TAG, " negotiated cipher suite: " + session.getCipherSuite()); - - final Certificate[] certs = session.getPeerCertificates(); - final X509Certificate x509 = (X509Certificate) certs[0]; - final X500Principal peer = x509.getSubjectX500Principal(); - - Log.d(TAG, " peer principal: " + peer.toString()); - final Collection> altNames1 = x509.getSubjectAlternativeNames(); - if (altNames1 != null) { - final List altNames = new ArrayList(); - for (final List aC : altNames1) { - if (!aC.isEmpty()) { - altNames.add((String) aC.get(1)); - } - } - Log.d(TAG, " peer alternative names: " + altNames); - } - - final X500Principal issuer = x509.getIssuerX500Principal(); - Log.d(TAG, " issuer principal: " + issuer.toString()); - final Collection> altNames2 = x509.getIssuerAlternativeNames(); - if (altNames2 != null) { - final List altNames = new ArrayList(); - for (final List aC : altNames2) { - if (!aC.isEmpty()) { - altNames.add((String) aC.get(1)); - } - } - Log.d(TAG, " issuer alternative names: " + altNames); - } - } catch (Exception ignore) { - } - } - - this.hostnameVerifier.verify(hostname, sslsock); - // verifyHostName() didn't blowup - good! - } catch (final IOException iox) { - // close the socket before re-throwing the exception - try { sslsock.close(); } catch (final Exception x) { /*ignore*/ } - throw iox; - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/SSLContextBuilder.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/SSLContextBuilder.java deleted file mode 100644 index 5d81fdaa..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/SSLContextBuilder.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.ssl; - -import java.net.Socket; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.Principal; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509KeyManager; -import javax.net.ssl.X509TrustManager; - -import org.apache.http.annotation.NotThreadSafe; - -/** - * Builder for {@link SSLContext} instances. - * - * @since 4.3 - */ -@NotThreadSafe -public class SSLContextBuilder { - - static final String TLS = "TLS"; - static final String SSL = "SSL"; - - private String protocol; - private Set keymanagers; - private Set trustmanagers; - private SecureRandom secureRandom; - - public SSLContextBuilder() { - super(); - this.keymanagers = new HashSet(); - this.trustmanagers = new HashSet(); - } - - public SSLContextBuilder useTLS() { - this.protocol = TLS; - return this; - } - - public SSLContextBuilder useSSL() { - this.protocol = SSL; - return this; - } - - public SSLContextBuilder useProtocol(final String protocol) { - this.protocol = protocol; - return this; - } - - public SSLContextBuilder setSecureRandom(final SecureRandom secureRandom) { - this.secureRandom = secureRandom; - return this; - } - - public SSLContextBuilder loadTrustMaterial( - final KeyStore truststore, - final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException { - final TrustManagerFactory tmfactory = TrustManagerFactory.getInstance( - TrustManagerFactory.getDefaultAlgorithm()); - tmfactory.init(truststore); - final TrustManager[] tms = tmfactory.getTrustManagers(); - if (tms != null) { - if (trustStrategy != null) { - for (int i = 0; i < tms.length; i++) { - final TrustManager tm = tms[i]; - if (tm instanceof X509TrustManager) { - tms[i] = new TrustManagerDelegate( - (X509TrustManager) tm, trustStrategy); - } - } - } - for (final TrustManager tm : tms) { - this.trustmanagers.add(tm); - } - } - return this; - } - - public SSLContextBuilder loadTrustMaterial( - final KeyStore truststore) throws NoSuchAlgorithmException, KeyStoreException { - return loadTrustMaterial(truststore, null); - } - - public SSLContextBuilder loadKeyMaterial( - final KeyStore keystore, - final char[] keyPassword) - throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException { - loadKeyMaterial(keystore, keyPassword, null); - return this; - } - - public SSLContextBuilder loadKeyMaterial( - final KeyStore keystore, - final char[] keyPassword, - final PrivateKeyStrategy aliasStrategy) - throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException { - final KeyManagerFactory kmfactory = KeyManagerFactory.getInstance( - KeyManagerFactory.getDefaultAlgorithm()); - kmfactory.init(keystore, keyPassword); - final KeyManager[] kms = kmfactory.getKeyManagers(); - if (kms != null) { - if (aliasStrategy != null) { - for (int i = 0; i < kms.length; i++) { - final KeyManager km = kms[i]; - if (km instanceof X509KeyManager) { - kms[i] = new KeyManagerDelegate( - (X509KeyManager) km, aliasStrategy); - } - } - } - for (final KeyManager km : kms) { - keymanagers.add(km); - } - } - return this; - } - - public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException { - final SSLContext sslcontext = SSLContext.getInstance( - this.protocol != null ? this.protocol : TLS); - sslcontext.init( - !keymanagers.isEmpty() ? keymanagers.toArray(new KeyManager[keymanagers.size()]) : null, - !trustmanagers.isEmpty() ? trustmanagers.toArray(new TrustManager[trustmanagers.size()]) : null, - secureRandom); - return sslcontext; - } - - static class TrustManagerDelegate implements X509TrustManager { - - private final X509TrustManager trustManager; - private final TrustStrategy trustStrategy; - - TrustManagerDelegate(final X509TrustManager trustManager, final TrustStrategy trustStrategy) { - super(); - this.trustManager = trustManager; - this.trustStrategy = trustStrategy; - } - - public void checkClientTrusted( - final X509Certificate[] chain, final String authType) throws CertificateException { - this.trustManager.checkClientTrusted(chain, authType); - } - - public void checkServerTrusted( - final X509Certificate[] chain, final String authType) throws CertificateException { - if (!this.trustStrategy.isTrusted(chain, authType)) { - this.trustManager.checkServerTrusted(chain, authType); - } - } - - public X509Certificate[] getAcceptedIssuers() { - return this.trustManager.getAcceptedIssuers(); - } - - } - - static class KeyManagerDelegate implements X509KeyManager { - - private final X509KeyManager keyManager; - private final PrivateKeyStrategy aliasStrategy; - - KeyManagerDelegate(final X509KeyManager keyManager, final PrivateKeyStrategy aliasStrategy) { - super(); - this.keyManager = keyManager; - this.aliasStrategy = aliasStrategy; - } - - public String[] getClientAliases( - final String keyType, final Principal[] issuers) { - return this.keyManager.getClientAliases(keyType, issuers); - } - - public String chooseClientAlias( - final String[] keyTypes, final Principal[] issuers, final Socket socket) { - final Map validAliases = new HashMap(); - for (final String keyType: keyTypes) { - final String[] aliases = this.keyManager.getClientAliases(keyType, issuers); - if (aliases != null) { - for (final String alias: aliases) { - validAliases.put(alias, - new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias))); - } - } - } - return this.aliasStrategy.chooseAlias(validAliases, socket); - } - - public String[] getServerAliases( - final String keyType, final Principal[] issuers) { - return this.keyManager.getServerAliases(keyType, issuers); - } - - public String chooseServerAlias( - final String keyType, final Principal[] issuers, final Socket socket) { - final Map validAliases = new HashMap(); - final String[] aliases = this.keyManager.getServerAliases(keyType, issuers); - if (aliases != null) { - for (final String alias: aliases) { - validAliases.put(alias, - new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias))); - } - } - return this.aliasStrategy.chooseAlias(validAliases, socket); - } - - public X509Certificate[] getCertificateChain(final String alias) { - return this.keyManager.getCertificateChain(alias); - } - - public PrivateKey getPrivateKey(final String alias) { - return this.keyManager.getPrivateKey(alias); - } - - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/SSLContexts.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/SSLContexts.java deleted file mode 100644 index 87a17a71..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/SSLContexts.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.ssl; - -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; - -import javax.net.ssl.SSLContext; - -import org.apache.http.annotation.Immutable; - -/** - * {@link SSLContext} factory methods. - * - * @since 4.3 - */ -@Immutable -public class SSLContexts { - - /** - * Creates default factory based on the standard JSSE trust material - * (cacerts file in the security properties directory). System properties - * are not taken into consideration. - * - * @return the default SSL socket factory - */ - public static SSLContext createDefault() throws SSLInitializationException { - try { - final SSLContext sslcontext = SSLContext.getInstance(SSLContextBuilder.TLS); - sslcontext.init(null, null, null); - return sslcontext; - } catch (final NoSuchAlgorithmException ex) { - throw new SSLInitializationException(ex.getMessage(), ex); - } catch (final KeyManagementException ex) { - throw new SSLInitializationException(ex.getMessage(), ex); - } - } - - /** - * Creates default SSL context based on system properties. This method obtains - * default SSL context by calling SSLContext.getInstance("Default"). - * Please note that Default algorithm is supported as of Java 6. - * This method will fall back onto {@link #createDefault()} when - * Default algorithm is not available. - * - * @return default system SSL context - */ - public static SSLContext createSystemDefault() throws SSLInitializationException { - try { - return SSLContext.getInstance("Default"); - } catch (final NoSuchAlgorithmException ex) { - return createDefault(); - } - } - - /** - * Creates custom SSL context. - * - * @return default system SSL context - */ - public static SSLContextBuilder custom() { - return new SSLContextBuilder(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/SSLInitializationException.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/SSLInitializationException.java deleted file mode 100644 index 51e05113..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/SSLInitializationException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.conn.ssl; - -public class SSLInitializationException extends IllegalStateException { - - private static final long serialVersionUID = -8243587425648536702L; - - public SSLInitializationException(final String message, final Throwable cause) { - super(message, cause); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/StrictHostnameVerifierHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/StrictHostnameVerifierHC4.java deleted file mode 100644 index 4fdc5d41..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/StrictHostnameVerifierHC4.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.ssl; - -import javax.net.ssl.SSLException; - -import org.apache.http.annotation.Immutable; - -/** - * The Strict HostnameVerifier works the same way as Sun Java 1.4, Sun - * Java 5, Sun Java 6-rc. It's also pretty close to IE6. This - * implementation appears to be compliant with RFC 2818 for dealing with - * wildcards. - *

    - * The hostname must match either the first CN, or any of the subject-alts. - * A wildcard can occur in the CN, and in any of the subject-alts. The - * one divergence from IE6 is how we only check the first CN. IE6 allows - * a match against any of the CNs present. We decided to follow in - * Sun Java 1.4's footsteps and only check the first CN. (If you need - * to check all the CN's, feel free to write your own implementation!). - *

    - * A wildcard such as "*.foo.com" matches only subdomains in the same - * level, for example "a.foo.com". It does not match deeper subdomains - * such as "a.b.foo.com". - * - * - * @since 4.0 - */ -@Immutable -public class StrictHostnameVerifierHC4 extends AbstractVerifierHC4 { - - public final void verify( - final String host, - final String[] cns, - final String[] subjectAlts) throws SSLException { - verify(host, cns, subjectAlts, true); - } - - @Override - public final String toString() { - return "STRICT"; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/TokenParser.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/TokenParser.java deleted file mode 100644 index 4fb032ec..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/TokenParser.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.ssl; - -import java.util.BitSet; - -import org.apache.http.message.ParserCursor; -import org.apache.http.util.CharArrayBuffer; - -/** - * Low level parser for header field elements. The parsing routines of this class are designed - * to produce near zero intermediate garbage and make no intermediate copies of input data. - *

    - * This class is immutable and thread safe. - * - * Temporary package-private copy of org.apache.http.message.TokenParser - */ -class TokenParser { - - public static BitSet INIT_BITSET(final int ... b) { - final BitSet bitset = new BitSet(); - for (final int aB : b) { - bitset.set(aB); - } - return bitset; - } - - /** US-ASCII CR, carriage return (13) */ - public static final char CR = '\r'; - - /** US-ASCII LF, line feed (10) */ - public static final char LF = '\n'; - - /** US-ASCII SP, space (32) */ - public static final char SP = ' '; - - /** US-ASCII HT, horizontal-tab (9) */ - public static final char HT = '\t'; - - /** Double quote */ - public static final char DQUOTE = '\"'; - - /** Backward slash / escape character */ - public static final char ESCAPE = '\\'; - - public static boolean isWhitespace(final char ch) { - return ch == SP || ch == HT || ch == CR || ch == LF; - } - - public static final TokenParser INSTANCE = new TokenParser(); - - /** - * Extracts from the sequence of chars a token terminated with any of the given delimiters - * discarding semantically insignificant whitespace characters. - * - * @param buf buffer with the sequence of chars to be parsed - * @param cursor defines the bounds and current position of the buffer - * @param delimiters set of delimiting characters. Can be null if the token - * is not delimited by any character. - */ - public String parseToken(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters) { - final StringBuilder dst = new StringBuilder(); - boolean whitespace = false; - while (!cursor.atEnd()) { - final char current = buf.charAt(cursor.getPos()); - if (delimiters != null && delimiters.get(current)) { - break; - } else if (isWhitespace(current)) { - skipWhiteSpace(buf, cursor); - whitespace = true; - } else { - if (whitespace && dst.length() > 0) { - dst.append(' '); - } - copyContent(buf, cursor, delimiters, dst); - whitespace = false; - } - } - return dst.toString(); - } - - /** - * Extracts from the sequence of chars a value which can be enclosed in quote marks and - * terminated with any of the given delimiters discarding semantically insignificant - * whitespace characters. - * - * @param buf buffer with the sequence of chars to be parsed - * @param cursor defines the bounds and current position of the buffer - * @param delimiters set of delimiting characters. Can be null if the value - * is not delimited by any character. - */ - public String parseValue(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters) { - final StringBuilder dst = new StringBuilder(); - boolean whitespace = false; - while (!cursor.atEnd()) { - final char current = buf.charAt(cursor.getPos()); - if (delimiters != null && delimiters.get(current)) { - break; - } else if (isWhitespace(current)) { - skipWhiteSpace(buf, cursor); - whitespace = true; - } else if (current == DQUOTE) { - if (whitespace && dst.length() > 0) { - dst.append(' '); - } - copyQuotedContent(buf, cursor, dst); - whitespace = false; - } else { - if (whitespace && dst.length() > 0) { - dst.append(' '); - } - copyUnquotedContent(buf, cursor, delimiters, dst); - whitespace = false; - } - } - return dst.toString(); - } - - /** - * Skips semantically insignificant whitespace characters and moves the cursor to the closest - * non-whitespace character. - * - * @param buf buffer with the sequence of chars to be parsed - * @param cursor defines the bounds and current position of the buffer - */ - public void skipWhiteSpace(final CharArrayBuffer buf, final ParserCursor cursor) { - int pos = cursor.getPos(); - final int indexFrom = cursor.getPos(); - final int indexTo = cursor.getUpperBound(); - for (int i = indexFrom; i < indexTo; i++) { - final char current = buf.charAt(i); - if (!isWhitespace(current)) { - break; - } else { - pos++; - } - } - cursor.updatePos(pos); - } - - /** - * Transfers content into the destination buffer until a whitespace character or any of - * the given delimiters is encountered. - * - * @param buf buffer with the sequence of chars to be parsed - * @param cursor defines the bounds and current position of the buffer - * @param delimiters set of delimiting characters. Can be null if the value - * is delimited by a whitespace only. - * @param dst destination buffer - */ - public void copyContent(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters, - final StringBuilder dst) { - int pos = cursor.getPos(); - final int indexFrom = cursor.getPos(); - final int indexTo = cursor.getUpperBound(); - for (int i = indexFrom; i < indexTo; i++) { - final char current = buf.charAt(i); - if ((delimiters != null && delimiters.get(current)) || isWhitespace(current)) { - break; - } else { - pos++; - dst.append(current); - } - } - cursor.updatePos(pos); - } - - /** - * Transfers content into the destination buffer until a whitespace character, a quote, - * or any of the given delimiters is encountered. - * - * @param buf buffer with the sequence of chars to be parsed - * @param cursor defines the bounds and current position of the buffer - * @param delimiters set of delimiting characters. Can be null if the value - * is delimited by a whitespace or a quote only. - * @param dst destination buffer - */ - public void copyUnquotedContent(final CharArrayBuffer buf, final ParserCursor cursor, - final BitSet delimiters, final StringBuilder dst) { - int pos = cursor.getPos(); - final int indexFrom = cursor.getPos(); - final int indexTo = cursor.getUpperBound(); - for (int i = indexFrom; i < indexTo; i++) { - final char current = buf.charAt(i); - if ((delimiters != null && delimiters.get(current)) - || isWhitespace(current) || current == DQUOTE) { - break; - } else { - pos++; - dst.append(current); - } - } - cursor.updatePos(pos); - } - - /** - * Transfers content enclosed with quote marks into the destination buffer. - * - * @param buf buffer with the sequence of chars to be parsed - * @param cursor defines the bounds and current position of the buffer - * @param dst destination buffer - */ - public void copyQuotedContent(final CharArrayBuffer buf, final ParserCursor cursor, - final StringBuilder dst) { - if (cursor.atEnd()) { - return; - } - int pos = cursor.getPos(); - int indexFrom = cursor.getPos(); - final int indexTo = cursor.getUpperBound(); - char current = buf.charAt(pos); - if (current != DQUOTE) { - return; - } - pos++; - indexFrom++; - boolean escaped = false; - for (int i = indexFrom; i < indexTo; i++, pos++) { - current = buf.charAt(i); - if (escaped) { - if (current != DQUOTE && current != ESCAPE) { - dst.append(ESCAPE); - } - dst.append(current); - escaped = false; - } else { - if (current == DQUOTE) { - pos++; - break; - } - if (current == ESCAPE) { - escaped = true; - } else if (current != CR && current != LF) { - dst.append(current); - } - } - } - cursor.updatePos(pos); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/TrustSelfSignedStrategy.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/TrustSelfSignedStrategy.java deleted file mode 100644 index 038b1eda..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/TrustSelfSignedStrategy.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.conn.ssl; - -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -/** - * A trust strategy that accepts self-signed certificates as trusted. Verification of all other - * certificates is done by the trust manager configured in the SSL context. - * - * @since 4.1 - */ -public class TrustSelfSignedStrategy implements TrustStrategy { - - public boolean isTrusted( - final X509Certificate[] chain, final String authType) throws CertificateException { - return chain.length == 1; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/TrustStrategy.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/TrustStrategy.java deleted file mode 100644 index 3af87778..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/TrustStrategy.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.conn.ssl; - -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -/** - * A strategy to establish trustworthiness of certificates without consulting the trust manager - * configured in the actual SSL context. This interface can be used to override the standard - * JSSE certificate verification process. - * - * @since 4.1 - */ -public interface TrustStrategy { - - /** - * Determines whether the certificate chain can be trusted without consulting the trust manager - * configured in the actual SSL context. This method can be used to override the standard JSSE - * certificate verification process. - *

    - * Please note that, if this method returns false, the trust manager configured - * in the actual SSL context can still clear the certificate as trusted. - * - * @param chain the peer certificate chain - * @param authType the authentication type based on the client certificate - * @return true if the certificate can be trusted without verification by - * the trust manager, false otherwise. - * @throws CertificateException thrown if the certificate is not trusted or invalid. - */ - boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException; - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/package-info.java deleted file mode 100644 index 292cb38d..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/ssl/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Client TLS/SSL support. - */ -package org.apache.http.conn.ssl; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/util/InetAddressUtilsHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/util/InetAddressUtilsHC4.java deleted file mode 100644 index 1e90308d..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/util/InetAddressUtilsHC4.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.util; - -import java.util.regex.Pattern; - -import org.apache.http.annotation.Immutable; - -/** - * A collection of utilities relating to InetAddresses. - * - * @since 4.0 - */ -@Immutable -public class InetAddressUtilsHC4 { - - private InetAddressUtilsHC4() { - } - - private static final String IPV4_BASIC_PATTERN_STRING = - "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}" + // initial 3 fields, 0-255 followed by . - "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"; // final field, 0-255 - - private static final Pattern IPV4_PATTERN = - Pattern.compile("^" + IPV4_BASIC_PATTERN_STRING + "$"); - - private static final Pattern IPV4_MAPPED_IPV6_PATTERN = // TODO does not allow for redundant leading zeros - Pattern.compile("^::[fF]{4}:" + IPV4_BASIC_PATTERN_STRING + "$"); - - private static final Pattern IPV6_STD_PATTERN = - Pattern.compile( - "^[0-9a-fA-F]{1,4}(:[0-9a-fA-F]{1,4}){7}$"); - - private static final Pattern IPV6_HEX_COMPRESSED_PATTERN = - Pattern.compile( - "^(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)" + // 0-6 hex fields - "::" + - "(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)$"); // 0-6 hex fields - - /* - * The above pattern is not totally rigorous as it allows for more than 7 hex fields in total - */ - private static final char COLON_CHAR = ':'; - - // Must not have more than 7 colons (i.e. 8 fields) - private static final int MAX_COLON_COUNT = 7; - - /** - * Checks whether the parameter is a valid IPv4 address - * - * @param input the address string to check for validity - * @return true if the input parameter is a valid IPv4 address - */ - public static boolean isIPv4Address(final String input) { - return IPV4_PATTERN.matcher(input).matches(); - } - - public static boolean isIPv4MappedIPv64Address(final String input) { - return IPV4_MAPPED_IPV6_PATTERN.matcher(input).matches(); - } - - /** - * Checks whether the parameter is a valid standard (non-compressed) IPv6 address - * - * @param input the address string to check for validity - * @return true if the input parameter is a valid standard (non-compressed) IPv6 address - */ - public static boolean isIPv6StdAddress(final String input) { - return IPV6_STD_PATTERN.matcher(input).matches(); - } - - /** - * Checks whether the parameter is a valid compressed IPv6 address - * - * @param input the address string to check for validity - * @return true if the input parameter is a valid compressed IPv6 address - */ - public static boolean isIPv6HexCompressedAddress(final String input) { - int colonCount = 0; - for(int i = 0; i < input.length(); i++) { - if (input.charAt(i) == COLON_CHAR) { - colonCount++; - } - } - return colonCount <= MAX_COLON_COUNT && IPV6_HEX_COMPRESSED_PATTERN.matcher(input).matches(); - } - - /** - * Checks whether the parameter is a valid IPv6 address (including compressed). - * - * @param input the address string to check for validity - * @return true if the input parameter is a valid standard or compressed IPv6 address - */ - public static boolean isIPv6Address(final String input) { - return isIPv6StdAddress(input) || isIPv6HexCompressedAddress(input); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/conn/util/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/conn/util/package-info.java deleted file mode 100644 index 7cf3d584..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/conn/util/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Connection utility classes. - */ -package org.apache.http.conn.util; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/cookie/CookieRestrictionViolationException.java b/lib/httpclient-android/src/main/java/org/apache/http/cookie/CookieRestrictionViolationException.java deleted file mode 100644 index ab9b3469..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/cookie/CookieRestrictionViolationException.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.cookie; - -import org.apache.http.annotation.Immutable; - -/** - * Signals that a cookie violates a restriction imposed by the cookie - * specification. - * - * @since 4.1 - */ -@Immutable -public class CookieRestrictionViolationException extends MalformedCookieException { - - private static final long serialVersionUID = 7371235577078589013L; - - /** - * Creates a new CookeFormatViolationException with a null detail - * message. - */ - public CookieRestrictionViolationException() { - super(); - } - - /** - * Creates a new CookeRestrictionViolationException with a specified - * message string. - * - * @param message The exception detail message - */ - public CookieRestrictionViolationException(final String message) { - super(message); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/cookie/CookieSpecProvider.java b/lib/httpclient-android/src/main/java/org/apache/http/cookie/CookieSpecProvider.java deleted file mode 100644 index fdb4f027..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/cookie/CookieSpecProvider.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.cookie; - -import org.apache.http.protocol.HttpContext; - -/** - * Factory for {@link CookieSpec} implementations. - * - * @since 4.3 - */ -public interface CookieSpecProvider { - - /** - * Creates an instance of {@link CookieSpec}. - * - * @return auth scheme. - */ - CookieSpec create(HttpContext context); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/cookie/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/cookie/package-info.java deleted file mode 100644 index 2c3563d9..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/cookie/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Client HTTP state management APIs. - */ -package org.apache.http.cookie; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/cookie/params/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/cookie/params/package-info.java deleted file mode 100644 index 5fe0162b..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/cookie/params/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Deprecated. - * @deprecated (4.3). - */ -package org.apache.http.cookie.params; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/entity/AbstractHttpEntityHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/entity/AbstractHttpEntityHC4.java deleted file mode 100644 index 75030da2..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/entity/AbstractHttpEntityHC4.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.entity; - -import java.io.IOException; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.message.BasicHeader; -import org.apache.http.protocol.HTTP; - -/** - * Abstract base class for entities. - * Provides the commonly used attributes for streamed and self-contained - * implementations of {@link HttpEntity HttpEntity}. - * - * @since 4.0 - */ -@NotThreadSafe -public abstract class AbstractHttpEntityHC4 implements HttpEntity { - - /** - * Buffer size for output stream processing. - * - * @since 4.3 - */ - protected static final int OUTPUT_BUFFER_SIZE = 4096; - - protected Header contentType; - protected Header contentEncoding; - protected boolean chunked; - - /** - * Protected default constructor. - * The contentType, contentEncoding and chunked attributes of the created object are set to - * null, null and false, respectively. - */ - protected AbstractHttpEntityHC4() { - super(); - } - - - /** - * Obtains the Content-Type header. - * The default implementation returns the value of the - * {@link #contentType contentType} attribute. - * - * @return the Content-Type header, or null - */ - public Header getContentType() { - return this.contentType; - } - - - /** - * Obtains the Content-Encoding header. - * The default implementation returns the value of the - * {@link #contentEncoding contentEncoding} attribute. - * - * @return the Content-Encoding header, or null - */ - public Header getContentEncoding() { - return this.contentEncoding; - } - - /** - * Obtains the 'chunked' flag. - * The default implementation returns the value of the - * {@link #chunked chunked} attribute. - * - * @return the 'chunked' flag - */ - public boolean isChunked() { - return this.chunked; - } - - - /** - * Specifies the Content-Type header. - * The default implementation sets the value of the - * {@link #contentType contentType} attribute. - * - * @param contentType the new Content-Encoding header, or - * null to unset - */ - public void setContentType(final Header contentType) { - this.contentType = contentType; - } - - /** - * Specifies the Content-Type header, as a string. - * The default implementation calls - * {@link #setContentType(Header) setContentType(Header)}. - * - * @param ctString the new Content-Type header, or - * null to unset - */ - public void setContentType(final String ctString) { - Header h = null; - if (ctString != null) { - h = new BasicHeader(HTTP.CONTENT_TYPE, ctString); - } - setContentType(h); - } - - - /** - * Specifies the Content-Encoding header. - * The default implementation sets the value of the - * {@link #contentEncoding contentEncoding} attribute. - * - * @param contentEncoding the new Content-Encoding header, or - * null to unset - */ - public void setContentEncoding(final Header contentEncoding) { - this.contentEncoding = contentEncoding; - } - - /** - * Specifies the Content-Encoding header, as a string. - * The default implementation calls - * {@link #setContentEncoding(Header) setContentEncoding(Header)}. - * - * @param ceString the new Content-Encoding header, or - * null to unset - */ - public void setContentEncoding(final String ceString) { - Header h = null; - if (ceString != null) { - h = new BasicHeader(HTTP.CONTENT_ENCODING, ceString); - } - setContentEncoding(h); - } - - - /** - * Specifies the 'chunked' flag. - *

    - * Note that the chunked setting is a hint only. - * If using HTTP/1.0, chunking is never performed. - * Otherwise, even if chunked is false, HttpClient must - * use chunk coding if the entity content length is - * unknown (-1). - *

    - * The default implementation sets the value of the - * {@link #chunked chunked} attribute. - * - * @param b the new 'chunked' flag - */ - public void setChunked(final boolean b) { - this.chunked = b; - } - - - /** - * The default implementation does not consume anything. - * - * @deprecated (4.1) Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that; - * otherwise call {@link #writeTo(java.io.OutputStream)} which is required to free the resources. - */ - @Deprecated - public void consumeContent() throws IOException { - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/entity/BasicHttpEntityHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/entity/BasicHttpEntityHC4.java deleted file mode 100644 index 6b1ecf97..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/entity/BasicHttpEntityHC4.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.entity; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.util.Args; -import org.apache.http.util.Asserts; - -/** - * A generic streamed, non-repeatable entity that obtains its content - * from an {@link InputStream}. - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicHttpEntityHC4 extends AbstractHttpEntityHC4 { - - private InputStream content; - private long length; - - /** - * Creates a new basic entity. - * The content is initially missing, the content length - * is set to a negative number. - */ - public BasicHttpEntityHC4() { - super(); - this.length = -1; - } - - public long getContentLength() { - return this.length; - } - - /** - * Obtains the content, once only. - * - * @return the content, if this is the first call to this method - * since {@link #setContent setContent} has been called - * - * @throws IllegalStateException - * if the content has not been provided - */ - public InputStream getContent() throws IllegalStateException { - Asserts.check(this.content != null, "Content has not been provided"); - return this.content; - } - - /** - * Tells that this entity is not repeatable. - * - * @return false - */ - public boolean isRepeatable() { - return false; - } - - /** - * Specifies the length of the content. - * - * @param len the number of bytes in the content, or - * a negative number to indicate an unknown length - */ - public void setContentLength(final long len) { - this.length = len; - } - - /** - * Specifies the content. - * - * @param instream the stream to return with the next call to - * {@link #getContent getContent} - */ - public void setContent(final InputStream instream) { - this.content = instream; - } - - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - final InputStream instream = getContent(); - try { - int l; - final byte[] tmp = new byte[OUTPUT_BUFFER_SIZE]; - while ((l = instream.read(tmp)) != -1) { - outstream.write(tmp, 0, l); - } - } finally { - instream.close(); - } - } - - public boolean isStreaming() { - return this.content != null; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/entity/BufferedHttpEntityHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/entity/BufferedHttpEntityHC4.java deleted file mode 100644 index 91d54d6a..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/entity/BufferedHttpEntityHC4.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.entity; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.http.HttpEntity; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.util.Args; -import org.apache.http.util.EntityUtilsHC4; - -/** - * A wrapping entity that buffers it content if necessary. - * The buffered entity is always repeatable. - * If the wrapped entity is repeatable itself, calls are passed through. - * If the wrapped entity is not repeatable, the content is read into a - * buffer once and provided from there as often as required. - * - * @since 4.0 - */ -@NotThreadSafe -public class BufferedHttpEntityHC4 extends HttpEntityWrapperHC4 { - - private final byte[] buffer; - - /** - * Creates a new buffered entity wrapper. - * - * @param entity the entity to wrap, not null - * @throws IllegalArgumentException if wrapped is null - */ - public BufferedHttpEntityHC4(final HttpEntity entity) throws IOException { - super(entity); - if (!entity.isRepeatable() || entity.getContentLength() < 0) { - this.buffer = EntityUtilsHC4.toByteArray(entity); - } else { - this.buffer = null; - } - } - - @Override - public long getContentLength() { - if (this.buffer != null) { - return this.buffer.length; - } else { - return super.getContentLength(); - } - } - - @Override - public InputStream getContent() throws IOException { - if (this.buffer != null) { - return new ByteArrayInputStream(this.buffer); - } else { - return super.getContent(); - } - } - - /** - * Tells that this entity does not have to be chunked. - * - * @return false - */ - @Override - public boolean isChunked() { - return (buffer == null) && super.isChunked(); - } - - /** - * Tells that this entity is repeatable. - * - * @return true - */ - @Override - public boolean isRepeatable() { - return true; - } - - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - if (this.buffer != null) { - outstream.write(this.buffer); - } else { - super.writeTo(outstream); - } - } - - - // non-javadoc, see interface HttpEntity - @Override - public boolean isStreaming() { - return (buffer == null) && super.isStreaming(); - } - -} // class BufferedHttpEntityHC4 diff --git a/lib/httpclient-android/src/main/java/org/apache/http/entity/ByteArrayEntityHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/entity/ByteArrayEntityHC4.java deleted file mode 100644 index 60075aba..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/entity/ByteArrayEntityHC4.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.entity; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.util.Args; - -/** - * A self contained, repeatable entity that obtains its content from a byte array. - * - * @since 4.0 - */ -@NotThreadSafe -public class ByteArrayEntityHC4 extends AbstractHttpEntityHC4 implements Cloneable { - - /** - * @deprecated (4.2) - */ - @Deprecated - protected final byte[] content; - private final byte[] b; - private final int off, len; - - /** - * @since 4.2 - */ - @SuppressWarnings("deprecation") - public ByteArrayEntityHC4(final byte[] b, final ContentType contentType) { - super(); - Args.notNull(b, "Source byte array"); - this.content = b; - this.b = b; - this.off = 0; - this.len = this.b.length; - if (contentType != null) { - setContentType(contentType.toString()); - } - } - - /** - * @since 4.2 - */ - @SuppressWarnings("deprecation") - public ByteArrayEntityHC4(final byte[] b, final int off, final int len, final ContentType contentType) { - super(); - Args.notNull(b, "Source byte array"); - if ((off < 0) || (off > b.length) || (len < 0) || - ((off + len) < 0) || ((off + len) > b.length)) { - throw new IndexOutOfBoundsException("off: " + off + " len: " + len + " b.length: " + b.length); - } - this.content = b; - this.b = b; - this.off = off; - this.len = len; - if (contentType != null) { - setContentType(contentType.toString()); - } - } - - public ByteArrayEntityHC4(final byte[] b) { - this(b, null); - } - - public ByteArrayEntityHC4(final byte[] b, final int off, final int len) { - this(b, off, len, null); - } - - public boolean isRepeatable() { - return true; - } - - public long getContentLength() { - return this.len; - } - - public InputStream getContent() { - return new ByteArrayInputStream(this.b, this.off, this.len); - } - - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - outstream.write(this.b, this.off, this.len); - outstream.flush(); - } - - - /** - * Tells that this entity is not streaming. - * - * @return false - */ - public boolean isStreaming() { - return false; - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - -} // class ByteArrayEntityHC4 diff --git a/lib/httpclient-android/src/main/java/org/apache/http/entity/ContentType.java b/lib/httpclient-android/src/main/java/org/apache/http/entity/ContentType.java deleted file mode 100644 index fe26ebed..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/entity/ContentType.java +++ /dev/null @@ -1,305 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.entity; - -import java.io.Serializable; -import java.nio.charset.Charset; -import java.nio.charset.UnsupportedCharsetException; -import java.util.Locale; - -import org.apache.http.Consts; -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.HttpEntity; -import org.apache.http.NameValuePair; -import org.apache.http.ParseException; -import org.apache.http.annotation.Immutable; -import org.apache.http.message.BasicHeaderValueFormatterHC4; -import org.apache.http.message.BasicHeaderValueParserHC4; -import org.apache.http.message.ParserCursor; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; -import org.apache.http.util.TextUtils; - -/** - * Content type information consisting of a MIME type and an optional charset. - *

    - * This class makes no attempts to verify validity of the MIME type. - * The input parameters of the {@link #create(String, String)} method, however, may not - * contain characters <">, <;>, <,> reserved by the HTTP specification. - * - * @since 4.2 - */ -@Immutable -public final class ContentType implements Serializable { - - private static final long serialVersionUID = -7768694718232371896L; - - // constants - public static final ContentType APPLICATION_ATOM_XML = create( - "application/atom+xml", Consts.ISO_8859_1); - public static final ContentType APPLICATION_FORM_URLENCODED = create( - "application/x-www-form-urlencoded", Consts.ISO_8859_1); - public static final ContentType APPLICATION_JSON = create( - "application/json", Consts.UTF_8); - public static final ContentType APPLICATION_OCTET_STREAM = create( - "application/octet-stream", (Charset) null); - public static final ContentType APPLICATION_SVG_XML = create( - "application/svg+xml", Consts.ISO_8859_1); - public static final ContentType APPLICATION_XHTML_XML = create( - "application/xhtml+xml", Consts.ISO_8859_1); - public static final ContentType APPLICATION_XML = create( - "application/xml", Consts.ISO_8859_1); - public static final ContentType MULTIPART_FORM_DATA = create( - "multipart/form-data", Consts.ISO_8859_1); - public static final ContentType TEXT_HTML = create( - "text/html", Consts.ISO_8859_1); - public static final ContentType TEXT_PLAIN = create( - "text/plain", Consts.ISO_8859_1); - public static final ContentType TEXT_XML = create( - "text/xml", Consts.ISO_8859_1); - public static final ContentType WILDCARD = create( - "*/*", (Charset) null); - - // defaults - public static final ContentType DEFAULT_TEXT = TEXT_PLAIN; - public static final ContentType DEFAULT_BINARY = APPLICATION_OCTET_STREAM; - - private final String mimeType; - private final Charset charset; - private final NameValuePair[] params; - - ContentType( - final String mimeType, - final Charset charset) { - this.mimeType = mimeType; - this.charset = charset; - this.params = null; - } - - ContentType( - final String mimeType, - final NameValuePair[] params) throws UnsupportedCharsetException { - this.mimeType = mimeType; - this.params = params; - final String s = getParameter("charset"); - this.charset = !TextUtils.isBlank(s) ? Charset.forName(s) : null; - } - - public String getMimeType() { - return this.mimeType; - } - - public Charset getCharset() { - return this.charset; - } - - /** - * @since 4.3 - */ - public String getParameter(final String name) { - Args.notEmpty(name, "Parameter name"); - if (this.params == null) { - return null; - } - for (final NameValuePair param: this.params) { - if (param.getName().equalsIgnoreCase(name)) { - return param.getValue(); - } - } - return null; - } - - /** - * Generates textual representation of this content type which can be used as the value - * of a Content-Type header. - */ - @Override - public String toString() { - final CharArrayBuffer buf = new CharArrayBuffer(64); - buf.append(this.mimeType); - if (this.params != null) { - buf.append("; "); - BasicHeaderValueFormatterHC4.INSTANCE.formatParameters(buf, this.params, false); - } else if (this.charset != null) { - buf.append("; charset="); - buf.append(this.charset.name()); - } - return buf.toString(); - } - - private static boolean valid(final String s) { - for (int i = 0; i < s.length(); i++) { - final char ch = s.charAt(i); - if (ch == '"' || ch == ',' || ch == ';') { - return false; - } - } - return true; - } - - /** - * Creates a new instance of {@link ContentType}. - * - * @param mimeType MIME type. It may not be null or empty. It may not contain - * characters <">, <;>, <,> reserved by the HTTP specification. - * @param charset charset. - * @return content type - */ - public static ContentType create(final String mimeType, final Charset charset) { - final String type = Args.notBlank(mimeType, "MIME type").toLowerCase(Locale.US); - Args.check(valid(type), "MIME type may not contain reserved characters"); - return new ContentType(type, charset); - } - - /** - * Creates a new instance of {@link ContentType} without a charset. - * - * @param mimeType MIME type. It may not be null or empty. It may not contain - * characters <">, <;>, <,> reserved by the HTTP specification. - * @return content type - */ - public static ContentType create(final String mimeType) { - return new ContentType(mimeType, (Charset) null); - } - - /** - * Creates a new instance of {@link ContentType}. - * - * @param mimeType MIME type. It may not be null or empty. It may not contain - * characters <">, <;>, <,> reserved by the HTTP specification. - * @param charset charset. It may not contain characters <">, <;>, <,> reserved by the HTTP - * specification. This parameter is optional. - * @return content type - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - */ - public static ContentType create( - final String mimeType, final String charset) throws UnsupportedCharsetException { - return create(mimeType, !TextUtils.isBlank(charset) ? Charset.forName(charset) : null); - } - - private static ContentType create(final HeaderElement helem) { - final String mimeType = helem.getName(); - final NameValuePair[] params = helem.getParameters(); - return new ContentType(mimeType, params != null && params.length > 0 ? params : null); - } - - /** - * Parses textual representation of Content-Type value. - * - * @param s text - * @return content type - * @throws ParseException if the given text does not represent a valid - * Content-Type value. - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - */ - public static ContentType parse( - final String s) throws ParseException, UnsupportedCharsetException { - Args.notNull(s, "Content type"); - final CharArrayBuffer buf = new CharArrayBuffer(s.length()); - buf.append(s); - final ParserCursor cursor = new ParserCursor(0, s.length()); - final HeaderElement[] elements = BasicHeaderValueParserHC4.INSTANCE.parseElements(buf, cursor); - if (elements.length > 0) { - return create(elements[0]); - } else { - throw new ParseException("Invalid content type: " + s); - } - } - - /** - * Extracts Content-Type value from {@link HttpEntity} exactly as - * specified by the Content-Type header of the entity. Returns null - * if not specified. - * - * @param entity HTTP entity - * @return content type - * @throws ParseException if the given text does not represent a valid - * Content-Type value. - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - */ - public static ContentType get( - final HttpEntity entity) throws ParseException, UnsupportedCharsetException { - if (entity == null) { - return null; - } - final Header header = entity.getContentType(); - if (header != null) { - final HeaderElement[] elements = header.getElements(); - if (elements.length > 0) { - return create(elements[0]); - } - } - return null; - } - - /** - * Extracts Content-Type value from {@link HttpEntity} or returns the default value - * {@link #DEFAULT_TEXT} if not explicitly specified. - * - * @param entity HTTP entity - * @return content type - * @throws ParseException if the given text does not represent a valid - * Content-Type value. - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - */ - public static ContentType getOrDefault( - final HttpEntity entity) throws ParseException, UnsupportedCharsetException { - final ContentType contentType = get(entity); - return contentType != null ? contentType : DEFAULT_TEXT; - } - - /** - * Creates a new instance with this MIME type and the given Charset. - * - * @param charset charset - * @return a new instance with this MIME type and the given Charset. - * @since 4.3 - */ - public ContentType withCharset(final Charset charset) { - return create(this.getMimeType(), charset); - } - - /** - * Creates a new instance with this MIME type and the given Charset name. - * - * @param charset name - * @return a new instance with this MIME type and the given Charset name. - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - * @since 4.3 - */ - public ContentType withCharset(final String charset) { - return create(this.getMimeType(), charset); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/entity/FileEntityHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/entity/FileEntityHC4.java deleted file mode 100644 index 3e6c52d4..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/entity/FileEntityHC4.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.entity; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.util.Args; - -/** - * A self contained, repeatable entity that obtains its content from a file. - * - * @since 4.0 - */ -@NotThreadSafe -public class FileEntityHC4 extends AbstractHttpEntityHC4 implements Cloneable { - - protected final File file; - - /** - * @deprecated (4.1.3) {@link #FileEntityHC4(File, ContentType)} - */ - @Deprecated - public FileEntityHC4(final File file, final String contentType) { - super(); - this.file = Args.notNull(file, "File"); - setContentType(contentType); - } - - /** - * @since 4.2 - */ - public FileEntityHC4(final File file, final ContentType contentType) { - super(); - this.file = Args.notNull(file, "File"); - if (contentType != null) { - setContentType(contentType.toString()); - } - } - - /** - * @since 4.2 - */ - public FileEntityHC4(final File file) { - super(); - this.file = Args.notNull(file, "File"); - } - - public boolean isRepeatable() { - return true; - } - - public long getContentLength() { - return this.file.length(); - } - - public InputStream getContent() throws IOException { - return new FileInputStream(this.file); - } - - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - final InputStream instream = new FileInputStream(this.file); - try { - final byte[] tmp = new byte[OUTPUT_BUFFER_SIZE]; - int l; - while ((l = instream.read(tmp)) != -1) { - outstream.write(tmp, 0, l); - } - outstream.flush(); - } finally { - instream.close(); - } - } - - /** - * Tells that this entity is not streaming. - * - * @return false - */ - public boolean isStreaming() { - return false; - } - - @Override - public Object clone() throws CloneNotSupportedException { - // File instance is considered immutable - // No need to make a copy of it - return super.clone(); - } - -} // class FileEntityHC4 diff --git a/lib/httpclient-android/src/main/java/org/apache/http/entity/HttpEntityWrapperHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/entity/HttpEntityWrapperHC4.java deleted file mode 100644 index c8ae0a7f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/entity/HttpEntityWrapperHC4.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.entity; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.util.Args; - -/** - * Base class for wrapping entities. - * Keeps a {@link #wrappedEntity wrappedEntity} and delegates all - * calls to it. Implementations of wrapping entities can derive - * from this class and need to override only those methods that - * should not be delegated to the wrapped entity. - * - * @since 4.0 - */ -@NotThreadSafe -public class HttpEntityWrapperHC4 implements HttpEntity { - - /** The wrapped entity. */ - protected HttpEntity wrappedEntity; - - /** - * Creates a new entity wrapper. - */ - public HttpEntityWrapperHC4(final HttpEntity wrappedEntity) { - super(); - this.wrappedEntity = Args.notNull(wrappedEntity, "Wrapped entity"); - } // constructor - - public boolean isRepeatable() { - return wrappedEntity.isRepeatable(); - } - - public boolean isChunked() { - return wrappedEntity.isChunked(); - } - - public long getContentLength() { - return wrappedEntity.getContentLength(); - } - - public Header getContentType() { - return wrappedEntity.getContentType(); - } - - public Header getContentEncoding() { - return wrappedEntity.getContentEncoding(); - } - - public InputStream getContent() - throws IOException { - return wrappedEntity.getContent(); - } - - public void writeTo(final OutputStream outstream) - throws IOException { - wrappedEntity.writeTo(outstream); - } - - public boolean isStreaming() { - return wrappedEntity.isStreaming(); - } - - /** - * @deprecated (4.1) Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that; - * otherwise call {@link #writeTo(OutputStream)} which is required to free the resources. - */ - @Deprecated - public void consumeContent() throws IOException { - wrappedEntity.consumeContent(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/entity/InputStreamEntityHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/entity/InputStreamEntityHC4.java deleted file mode 100644 index 9570e190..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/entity/InputStreamEntityHC4.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.entity; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.util.Args; - -/** - * A streamed, non-repeatable entity that obtains its content from - * an {@link InputStream}. - * - * @since 4.0 - */ -@NotThreadSafe -public class InputStreamEntityHC4 extends AbstractHttpEntityHC4 { - - private final InputStream content; - private final long length; - - /** - * Creates an entity with an unknown length. - * Equivalent to {@code new InputStreamEntityHC4(instream, -1)}. - * - * @param instream input stream - * @throws IllegalArgumentException if {@code instream} is {@code null} - * @since 4.3 - */ - public InputStreamEntityHC4(final InputStream instream) { - this(instream, -1); - } - - /** - * Creates an entity with a specified content length. - * - * @param instream input stream - * @param length of the input stream, {@code -1} if unknown - * @throws IllegalArgumentException if {@code instream} is {@code null} - */ - public InputStreamEntityHC4(final InputStream instream, final long length) { - this(instream, length, null); - } - - /** - * Creates an entity with a content type and unknown length. - * Equivalent to {@code new InputStreamEntityHC4(instream, -1, contentType)}. - * - * @param instream input stream - * @param contentType content type - * @throws IllegalArgumentException if {@code instream} is {@code null} - * @since 4.3 - */ - public InputStreamEntityHC4(final InputStream instream, final ContentType contentType) { - this(instream, -1, contentType); - } - - /** - * @param instream input stream - * @param length of the input stream, {@code -1} if unknown - * @param contentType for specifying the {@code Content-Type} header, may be {@code null} - * @throws IllegalArgumentException if {@code instream} is {@code null} - * @since 4.2 - */ - public InputStreamEntityHC4(final InputStream instream, final long length, final ContentType contentType) { - super(); - this.content = Args.notNull(instream, "Source input stream"); - this.length = length; - if (contentType != null) { - setContentType(contentType.toString()); - } - } - - public boolean isRepeatable() { - return false; - } - - /** - * @return the content length or {@code -1} if unknown - */ - public long getContentLength() { - return this.length; - } - - public InputStream getContent() throws IOException { - return this.content; - } - - /** - * Writes bytes from the {@code InputStream} this entity was constructed - * with to an {@code OutputStream}. The content length - * determines how many bytes are written. If the length is unknown ({@code -1}), the - * stream will be completely consumed (to the end of the stream). - * - */ - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - final InputStream instream = this.content; - try { - final byte[] buffer = new byte[OUTPUT_BUFFER_SIZE]; - int l; - if (this.length < 0) { - // consume until EOF - while ((l = instream.read(buffer)) != -1) { - outstream.write(buffer, 0, l); - } - } else { - // consume no more than length - long remaining = this.length; - while (remaining > 0) { - l = instream.read(buffer, 0, (int)Math.min(OUTPUT_BUFFER_SIZE, remaining)); - if (l == -1) { - break; - } - outstream.write(buffer, 0, l); - remaining -= l; - } - } - } finally { - instream.close(); - } - } - - public boolean isStreaming() { - return true; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/entity/SerializableEntityHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/entity/SerializableEntityHC4.java deleted file mode 100644 index 34c5e1bf..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/entity/SerializableEntityHC4.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.entity; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.io.Serializable; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.util.Args; - -/** - * A streamed entity that obtains its content from a {@link Serializable}. - * The content obtained from the {@link Serializable} instance can - * optionally be buffered in a byte array in order to make the - * entity self-contained and repeatable. - * - * @since 4.0 - */ -@NotThreadSafe -public class SerializableEntityHC4 extends AbstractHttpEntityHC4 { - - private byte[] objSer; - - private Serializable objRef; - - /** - * Creates new instance of this class. - * - * @param ser input - * @param bufferize tells whether the content should be - * stored in an internal buffer - * @throws IOException in case of an I/O error - */ - public SerializableEntityHC4(final Serializable ser, final boolean bufferize) throws IOException { - super(); - Args.notNull(ser, "Source object"); - if (bufferize) { - createBytes(ser); - } else { - this.objRef = ser; - } - } - - /** - * @since 4.3 - */ - public SerializableEntityHC4(final Serializable ser) { - super(); - Args.notNull(ser, "Source object"); - this.objRef = ser; - } - - private void createBytes(final Serializable ser) throws IOException { - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final ObjectOutputStream out = new ObjectOutputStream(baos); - out.writeObject(ser); - out.flush(); - this.objSer = baos.toByteArray(); - } - - public InputStream getContent() throws IOException, IllegalStateException { - if (this.objSer == null) { - createBytes(this.objRef); - } - return new ByteArrayInputStream(this.objSer); - } - - public long getContentLength() { - if (this.objSer == null) { - return -1; - } else { - return this.objSer.length; - } - } - - public boolean isRepeatable() { - return true; - } - - public boolean isStreaming() { - return this.objSer == null; - } - - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - if (this.objSer == null) { - final ObjectOutputStream out = new ObjectOutputStream(outstream); - out.writeObject(this.objRef); - out.flush(); - } else { - outstream.write(this.objSer); - outstream.flush(); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/entity/StringEntityHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/entity/StringEntityHC4.java deleted file mode 100644 index 82e71b80..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/entity/StringEntityHC4.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.entity; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.nio.charset.UnsupportedCharsetException; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.Args; - -/** - * A self contained, repeatable entity that obtains its content from - * a {@link String}. - * - * @since 4.0 - */ -@NotThreadSafe -public class StringEntityHC4 extends AbstractHttpEntityHC4 implements Cloneable { - - protected final byte[] content; - - /** - * Creates a StringEntityHC4 with the specified content and content type. - * - * @param string content to be used. Not {@code null}. - * @param contentType content type to be used. May be {@code null}, in which case the default - * MIME type {@link ContentType#TEXT_PLAIN} is assumed. - * - * @throws IllegalArgumentException if the string parameter is null - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - * @since 4.2 - */ - public StringEntityHC4(final String string, final ContentType contentType) throws UnsupportedCharsetException { - super(); - Args.notNull(string, "Source string"); - Charset charset = contentType != null ? contentType.getCharset() : null; - if (charset == null) { - charset = Charset.forName(HTTP.DEFAULT_CONTENT_CHARSET); - } - try { - this.content = string.getBytes(charset.name()); - } catch (final UnsupportedEncodingException ex) { - // should never happen - throw new UnsupportedCharsetException(charset.name()); - } - if (contentType != null) { - setContentType(contentType.toString()); - } - } - - /** - * Creates a StringEntityHC4 with the specified content, MIME type and charset - * - * @param string content to be used. Not {@code null}. - * @param mimeType MIME type to be used. May be {@code null}, in which case the default - * is {@link HTTP#PLAIN_TEXT_TYPE} i.e. "text/plain" - * @param charset character set to be used. May be {@code null}, in which case the default - * is {@link HTTP#DEFAULT_CONTENT_CHARSET} i.e. "ISO-8859-1" - * @throws UnsupportedEncodingException If the named charset is not supported. - * - * @since 4.1 - * @throws IllegalArgumentException if the string parameter is null - * - * @deprecated (4.1.3) use {@link #StringEntityHC4(String, ContentType)} - */ - @Deprecated - public StringEntityHC4( - final String string, final String mimeType, final String charset) throws UnsupportedEncodingException { - super(); - Args.notNull(string, "Source string"); - final String mt = mimeType != null ? mimeType : HTTP.PLAIN_TEXT_TYPE; - final String cs = charset != null ? charset :HTTP.DEFAULT_CONTENT_CHARSET; - this.content = string.getBytes(cs); - setContentType(mt + HTTP.CHARSET_PARAM + cs); - } - - /** - * Creates a StringEntityHC4 with the specified content and charset. The MIME type defaults - * to "text/plain". - * - * @param string content to be used. Not {@code null}. - * @param charset character set to be used. May be {@code null}, in which case the default - * is {@link HTTP#DEFAULT_CONTENT_CHARSET} is assumed - * - * @throws IllegalArgumentException if the string parameter is null - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - */ - public StringEntityHC4(final String string, final String charset) - throws UnsupportedCharsetException { - this(string, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), charset)); - } - - /** - * Creates a StringEntityHC4 with the specified content and charset. The MIME type defaults - * to "text/plain". - * - * @param string content to be used. Not {@code null}. - * @param charset character set to be used. May be {@code null}, in which case the default - * is {@link HTTP#DEFAULT_CONTENT_CHARSET} is assumed - * - * @throws IllegalArgumentException if the string parameter is null - * - * @since 4.2 - */ - public StringEntityHC4(final String string, final Charset charset) { - this(string, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), charset)); - } - - /** - * Creates a StringEntityHC4 with the specified content. The content type defaults to - * {@link ContentType#TEXT_PLAIN}. - * - * @param string content to be used. Not {@code null}. - * - * @throws IllegalArgumentException if the string parameter is null - * @throws UnsupportedEncodingException if the default HTTP charset is not supported. - */ - public StringEntityHC4(final String string) - throws UnsupportedEncodingException { - this(string, ContentType.DEFAULT_TEXT); - } - - public boolean isRepeatable() { - return true; - } - - public long getContentLength() { - return this.content.length; - } - - public InputStream getContent() throws IOException { - return new ByteArrayInputStream(this.content); - } - - public void writeTo(final OutputStream outstream) throws IOException { - Args.notNull(outstream, "Output stream"); - outstream.write(this.content); - outstream.flush(); - } - - /** - * Tells that this entity is not streaming. - * - * @return false - */ - public boolean isStreaming() { - return false; - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - -} // class StringEntityHC4 diff --git a/lib/httpclient-android/src/main/java/org/apache/http/entity/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/entity/package-info.java deleted file mode 100644 index 83b867a9..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/entity/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Core HTTP entity implementations. - */ -package org.apache.http.entity; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/BHttpConnectionBase.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/BHttpConnectionBase.java deleted file mode 100644 index 2e221407..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/BHttpConnectionBase.java +++ /dev/null @@ -1,393 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; - -import org.apache.http.Header; -import org.apache.http.HttpConnection; -import org.apache.http.HttpConnectionMetrics; -import org.apache.http.HttpEntity; -import org.apache.http.HttpException; -import org.apache.http.HttpInetConnection; -import org.apache.http.HttpMessage; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.config.MessageConstraints; -import org.apache.http.entity.BasicHttpEntityHC4; -import org.apache.http.entity.ContentLengthStrategy; -import org.apache.http.impl.entity.LaxContentLengthStrategyHC4; -import org.apache.http.impl.entity.StrictContentLengthStrategyHC4; -import org.apache.http.impl.io.ChunkedInputStreamHC4; -import org.apache.http.impl.io.ChunkedOutputStreamHC4; -import org.apache.http.impl.io.ContentLengthInputStreamHC4; -import org.apache.http.impl.io.ContentLengthOutputStreamHC4; -import org.apache.http.impl.io.HttpTransportMetricsImpl; -import org.apache.http.impl.io.IdentityInputStreamHC4; -import org.apache.http.impl.io.IdentityOutputStreamHC4; -import org.apache.http.impl.io.SessionInputBufferImpl; -import org.apache.http.impl.io.SessionOutputBufferImpl; -import org.apache.http.io.SessionInputBuffer; -import org.apache.http.io.SessionOutputBuffer; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.Args; -import org.apache.http.util.Asserts; -import org.apache.http.util.NetUtils; - -/** - * This class serves as a base for all {@link HttpConnection} implementations and provides - * functionality common to both client and server HTTP connections. - * - * @since 4.0 - */ -@NotThreadSafe -public class BHttpConnectionBase implements HttpConnection, HttpInetConnection { - - private final SessionInputBufferImpl inbuffer; - private final SessionOutputBufferImpl outbuffer; - private final HttpConnectionMetricsImpl connMetrics; - private final ContentLengthStrategy incomingContentStrategy; - private final ContentLengthStrategy outgoingContentStrategy; - - private volatile boolean open; - private volatile Socket socket; - - /** - * Creates new instance of BHttpConnectionBase. - * - * @param buffersize buffer size. Must be a positive number. - * @param fragmentSizeHint fragment size hint. - * @param chardecoder decoder to be used for decoding HTTP protocol elements. - * If null simple type cast will be used for byte to char conversion. - * @param charencoder encoder to be used for encoding HTTP protocol elements. - * If null simple type cast will be used for char to byte conversion. - * @param constraints Message constraints. If null - * {@link MessageConstraints#DEFAULT} will be used. - * @param incomingContentStrategy incoming content length strategy. If null - * {@link LaxContentLengthStrategyHC4#INSTANCE} will be used. - * @param outgoingContentStrategy outgoing content length strategy. If null - * {@link StrictContentLengthStrategyHC4#INSTANCE} will be used. - */ - protected BHttpConnectionBase( - final int buffersize, - final int fragmentSizeHint, - final CharsetDecoder chardecoder, - final CharsetEncoder charencoder, - final MessageConstraints constraints, - final ContentLengthStrategy incomingContentStrategy, - final ContentLengthStrategy outgoingContentStrategy) { - super(); - Args.positive(buffersize, "Buffer size"); - final HttpTransportMetricsImpl inTransportMetrics = new HttpTransportMetricsImpl(); - final HttpTransportMetricsImpl outTransportMetrics = new HttpTransportMetricsImpl(); - this.inbuffer = new SessionInputBufferImpl(inTransportMetrics, buffersize, -1, - constraints != null ? constraints : MessageConstraints.DEFAULT, chardecoder); - this.outbuffer = new SessionOutputBufferImpl(outTransportMetrics, buffersize, fragmentSizeHint, - charencoder); - this.connMetrics = new HttpConnectionMetricsImpl(inTransportMetrics, outTransportMetrics); - this.incomingContentStrategy = incomingContentStrategy != null ? incomingContentStrategy : - LaxContentLengthStrategyHC4.INSTANCE; - this.outgoingContentStrategy = outgoingContentStrategy != null ? outgoingContentStrategy : - StrictContentLengthStrategyHC4.INSTANCE; - } - - protected void ensureOpen() throws IOException { - Asserts.check(this.open, "Connection is not open"); - if (!this.inbuffer.isBound()) { - this.inbuffer.bind(getSocketInputStream(this.socket)); - } - if (!this.outbuffer.isBound()) { - this.outbuffer.bind(getSocketOutputStream(this.socket)); - } - } - - protected InputStream getSocketInputStream(final Socket socket) throws IOException { - return socket.getInputStream(); - } - - protected OutputStream getSocketOutputStream(final Socket socket) throws IOException { - return socket.getOutputStream(); - } - - /** - * Binds this connection to the given {@link Socket}. This socket will be - * used by the connection to send and receive data. - *

    - * After this method's execution the connection status will be reported - * as open and the {@link #isOpen()} will return true. - * - * @param socket the socket. - * @throws IOException in case of an I/O error. - */ - protected void bind(final Socket socket) throws IOException { - Args.notNull(socket, "Socket"); - this.socket = socket; - this.open = true; - this.inbuffer.bind(null); - this.outbuffer.bind(null); - } - - protected SessionInputBuffer getSessionInputBuffer() { - return this.inbuffer; - } - - protected SessionOutputBuffer getSessionOutputBuffer() { - return this.outbuffer; - } - - protected void doFlush() throws IOException { - this.outbuffer.flush(); - } - - public boolean isOpen() { - return this.open; - } - - protected Socket getSocket() { - return this.socket; - } - - protected OutputStream createOutputStream( - final long len, - final SessionOutputBuffer outbuffer) { - if (len == ContentLengthStrategy.CHUNKED) { - return new ChunkedOutputStreamHC4(2048, outbuffer); - } else if (len == ContentLengthStrategy.IDENTITY) { - return new IdentityOutputStreamHC4(outbuffer); - } else { - return new ContentLengthOutputStreamHC4(outbuffer, len); - } - } - - protected OutputStream prepareOutput(final HttpMessage message) throws HttpException { - final long len = this.outgoingContentStrategy.determineLength(message); - return createOutputStream(len, this.outbuffer); - } - - protected InputStream createInputStream( - final long len, - final SessionInputBuffer inbuffer) { - if (len == ContentLengthStrategy.CHUNKED) { - return new ChunkedInputStreamHC4(inbuffer); - } else if (len == ContentLengthStrategy.IDENTITY) { - return new IdentityInputStreamHC4(inbuffer); - } else { - return new ContentLengthInputStreamHC4(inbuffer, len); - } - } - - protected HttpEntity prepareInput(final HttpMessage message) throws HttpException { - final BasicHttpEntityHC4 entity = new BasicHttpEntityHC4(); - - final long len = this.incomingContentStrategy.determineLength(message); - final InputStream instream = createInputStream(len, this.inbuffer); - if (len == ContentLengthStrategy.CHUNKED) { - entity.setChunked(true); - entity.setContentLength(-1); - entity.setContent(instream); - } else if (len == ContentLengthStrategy.IDENTITY) { - entity.setChunked(false); - entity.setContentLength(-1); - entity.setContent(instream); - } else { - entity.setChunked(false); - entity.setContentLength(len); - entity.setContent(instream); - } - - final Header contentTypeHeader = message.getFirstHeader(HTTP.CONTENT_TYPE); - if (contentTypeHeader != null) { - entity.setContentType(contentTypeHeader); - } - final Header contentEncodingHeader = message.getFirstHeader(HTTP.CONTENT_ENCODING); - if (contentEncodingHeader != null) { - entity.setContentEncoding(contentEncodingHeader); - } - return entity; - } - - public InetAddress getLocalAddress() { - if (this.socket != null) { - return this.socket.getLocalAddress(); - } else { - return null; - } - } - - public int getLocalPort() { - if (this.socket != null) { - return this.socket.getLocalPort(); - } else { - return -1; - } - } - - public InetAddress getRemoteAddress() { - if (this.socket != null) { - return this.socket.getInetAddress(); - } else { - return null; - } - } - - public int getRemotePort() { - if (this.socket != null) { - return this.socket.getPort(); - } else { - return -1; - } - } - - public void setSocketTimeout(final int timeout) { - if (this.socket != null) { - try { - this.socket.setSoTimeout(timeout); - } catch (final SocketException ignore) { - // It is not quite clear from the Sun's documentation if there are any - // other legitimate cases for a socket exception to be thrown when setting - // SO_TIMEOUT besides the socket being already closed - } - } - } - - public int getSocketTimeout() { - if (this.socket != null) { - try { - return this.socket.getSoTimeout(); - } catch (final SocketException ignore) { - return -1; - } - } else { - return -1; - } - } - - public void shutdown() throws IOException { - this.open = false; - final Socket tmpsocket = this.socket; - if (tmpsocket != null) { - tmpsocket.close(); - } - } - - public void close() throws IOException { - if (!this.open) { - return; - } - this.open = false; - final Socket sock = this.socket; - try { - this.inbuffer.clear(); - this.outbuffer.flush(); - try { - try { - sock.shutdownOutput(); - } catch (final IOException ignore) { - } - try { - sock.shutdownInput(); - } catch (final IOException ignore) { - } - } catch (final UnsupportedOperationException ignore) { - // if one isn't supported, the other one isn't either - } - } finally { - sock.close(); - } - } - - private int fillInputBuffer(final int timeout) throws IOException { - final int oldtimeout = this.socket.getSoTimeout(); - try { - this.socket.setSoTimeout(timeout); - return this.inbuffer.fillBuffer(); - } finally { - this.socket.setSoTimeout(oldtimeout); - } - } - - protected boolean awaitInput(final int timeout) throws IOException { - if (this.inbuffer.hasBufferedData()) { - return true; - } - fillInputBuffer(timeout); - return this.inbuffer.hasBufferedData(); - } - - public boolean isStale() { - if (!isOpen()) { - return true; - } - try { - final int bytesRead = fillInputBuffer(1); - return bytesRead < 0; - } catch (final SocketTimeoutException ex) { - return false; - } catch (final IOException ex) { - return true; - } - } - - protected void incrementRequestCount() { - this.connMetrics.incrementRequestCount(); - } - - protected void incrementResponseCount() { - this.connMetrics.incrementResponseCount(); - } - - public HttpConnectionMetrics getMetrics() { - return this.connMetrics; - } - - @Override - public String toString() { - if (this.socket != null) { - final StringBuilder buffer = new StringBuilder(); - final SocketAddress remoteAddress = this.socket.getRemoteSocketAddress(); - final SocketAddress localAddress = this.socket.getLocalSocketAddress(); - if (remoteAddress != null && localAddress != null) { - NetUtils.formatAddress(buffer, localAddress); - buffer.append("<->"); - NetUtils.formatAddress(buffer, remoteAddress); - } - return buffer.toString(); - } else { - return "[Not bound]"; - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/ConnSupport.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/ConnSupport.java deleted file mode 100644 index a957629f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/ConnSupport.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl; - -import org.apache.http.config.ConnectionConfig; - -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CodingErrorAction; - -/** - * Connection support methods. - * - * @since 4.3 - */ -public final class ConnSupport { - - public static CharsetDecoder createDecoder(final ConnectionConfig cconfig) { - if (cconfig == null) { - return null; - } - final Charset charset = cconfig.getCharset(); - final CodingErrorAction malformed = cconfig.getMalformedInputAction(); - final CodingErrorAction unmappable = cconfig.getUnmappableInputAction(); - if (charset != null) { - return charset.newDecoder() - .onMalformedInput(malformed != null ? malformed : CodingErrorAction.REPORT) - .onUnmappableCharacter(unmappable != null ? unmappable: CodingErrorAction.REPORT); - } else { - return null; - } - } - - public static CharsetEncoder createEncoder(final ConnectionConfig cconfig) { - if (cconfig == null) { - return null; - } - final Charset charset = cconfig.getCharset(); - if (charset != null) { - final CodingErrorAction malformed = cconfig.getMalformedInputAction(); - final CodingErrorAction unmappable = cconfig.getUnmappableInputAction(); - return charset.newEncoder() - .onMalformedInput(malformed != null ? malformed : CodingErrorAction.REPORT) - .onUnmappableCharacter(unmappable != null ? unmappable: CodingErrorAction.REPORT); - } else { - return null; - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultBHttpClientConnection.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultBHttpClientConnection.java deleted file mode 100644 index e40a6f32..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultBHttpClientConnection.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl; - -import java.io.IOException; -import java.io.OutputStream; -import java.net.Socket; -import java.net.SocketTimeoutException; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; - -import org.apache.http.HttpClientConnection; -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.config.MessageConstraints; -import org.apache.http.entity.ContentLengthStrategy; -import org.apache.http.impl.io.DefaultHttpRequestWriterFactory; -import org.apache.http.impl.io.DefaultHttpResponseParserFactory; -import org.apache.http.io.HttpMessageParser; -import org.apache.http.io.HttpMessageParserFactory; -import org.apache.http.io.HttpMessageWriter; -import org.apache.http.io.HttpMessageWriterFactory; -import org.apache.http.util.Args; - -/** - * Default implementation of {@link HttpClientConnection}. - * - * @since 4.3 - */ -@NotThreadSafe -public class DefaultBHttpClientConnection extends BHttpConnectionBase - implements HttpClientConnection { - - private final HttpMessageParser responseParser; - private final HttpMessageWriter requestWriter; - - /** - * Creates new instance of DefaultBHttpClientConnection. - * - * @param buffersize buffer size. Must be a positive number. - * @param fragmentSizeHint fragment size hint. - * @param chardecoder decoder to be used for decoding HTTP protocol elements. - * If null simple type cast will be used for byte to char conversion. - * @param charencoder encoder to be used for encoding HTTP protocol elements. - * If null simple type cast will be used for char to byte conversion. - * @param constraints Message constraints. If null - * {@link MessageConstraints#DEFAULT} will be used. - * @param incomingContentStrategy incoming content length strategy. If null - * {@link org.apache.http.impl.entity.LaxContentLengthStrategyHC4#INSTANCE} will be used. - * @param outgoingContentStrategy outgoing content length strategy. If null - * {@link org.apache.http.impl.entity.StrictContentLengthStrategyHC4#INSTANCE} will be used. - * @param requestWriterFactory request writer factory. If null - * {@link DefaultHttpRequestWriterFactory#INSTANCE} will be used. - * @param responseParserFactory response parser factory. If null - * {@link DefaultHttpResponseParserFactory#INSTANCE} will be used. - */ - public DefaultBHttpClientConnection( - final int buffersize, - final int fragmentSizeHint, - final CharsetDecoder chardecoder, - final CharsetEncoder charencoder, - final MessageConstraints constraints, - final ContentLengthStrategy incomingContentStrategy, - final ContentLengthStrategy outgoingContentStrategy, - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory) { - super(buffersize, fragmentSizeHint, chardecoder, charencoder, - constraints, incomingContentStrategy, outgoingContentStrategy); - this.requestWriter = (requestWriterFactory != null ? requestWriterFactory : - DefaultHttpRequestWriterFactory.INSTANCE).create(getSessionOutputBuffer()); - this.responseParser = (responseParserFactory != null ? responseParserFactory : - DefaultHttpResponseParserFactory.INSTANCE).create(getSessionInputBuffer(), constraints); - } - - public DefaultBHttpClientConnection( - final int buffersize, - final CharsetDecoder chardecoder, - final CharsetEncoder charencoder, - final MessageConstraints constraints) { - this(buffersize, buffersize, chardecoder, charencoder, constraints, null, null, null, null); - } - - public DefaultBHttpClientConnection(final int buffersize) { - this(buffersize, buffersize, null, null, null, null, null, null, null); - } - - protected void onResponseReceived(final HttpResponse response) { - } - - protected void onRequestSubmitted(final HttpRequest request) { - } - - @Override - public void bind(final Socket socket) throws IOException { - super.bind(socket); - } - - public boolean isResponseAvailable(final int timeout) throws IOException { - ensureOpen(); - try { - return awaitInput(timeout); - } catch (final SocketTimeoutException ex) { - return false; - } - } - - public void sendRequestHeader(final HttpRequest request) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - ensureOpen(); - this.requestWriter.write(request); - onRequestSubmitted(request); - incrementRequestCount(); - } - - public void sendRequestEntity(final HttpEntityEnclosingRequest request) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - ensureOpen(); - final HttpEntity entity = request.getEntity(); - if (entity == null) { - return; - } - final OutputStream outstream = prepareOutput(request); - entity.writeTo(outstream); - outstream.close(); - } - - public HttpResponse receiveResponseHeader() throws HttpException, IOException { - ensureOpen(); - final HttpResponse response = (HttpResponse) this.responseParser.parse(); - onResponseReceived(response); - if (response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK) { - incrementResponseCount(); - } - return response; - } - - public void receiveResponseEntity( - final HttpResponse response) throws HttpException, IOException { - Args.notNull(response, "HTTP response"); - ensureOpen(); - final HttpEntity entity = prepareInput(response); - response.setEntity(entity); - } - - public void flush() throws IOException { - ensureOpen(); - doFlush(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultBHttpClientConnectionFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultBHttpClientConnectionFactory.java deleted file mode 100644 index f44be115..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultBHttpClientConnectionFactory.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl; - -import org.apache.http.HttpConnectionFactory; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.Immutable; -import org.apache.http.config.ConnectionConfig; -import org.apache.http.entity.ContentLengthStrategy; -import org.apache.http.io.HttpMessageParserFactory; -import org.apache.http.io.HttpMessageWriterFactory; - -import java.io.IOException; -import java.net.Socket; - -/** - * Default factory for {@link org.apache.http.HttpClientConnection}s. - * - * @since 4.3 - */ -@Immutable -public class DefaultBHttpClientConnectionFactory - implements HttpConnectionFactory { - - public static final DefaultBHttpClientConnectionFactory INSTANCE = new DefaultBHttpClientConnectionFactory(); - - private final ConnectionConfig cconfig; - private final ContentLengthStrategy incomingContentStrategy; - private final ContentLengthStrategy outgoingContentStrategy; - private final HttpMessageWriterFactory requestWriterFactory; - private final HttpMessageParserFactory responseParserFactory; - - public DefaultBHttpClientConnectionFactory( - final ConnectionConfig cconfig, - final ContentLengthStrategy incomingContentStrategy, - final ContentLengthStrategy outgoingContentStrategy, - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory) { - super(); - this.cconfig = cconfig != null ? cconfig : ConnectionConfig.DEFAULT; - this.incomingContentStrategy = incomingContentStrategy; - this.outgoingContentStrategy = outgoingContentStrategy; - this.requestWriterFactory = requestWriterFactory; - this.responseParserFactory = responseParserFactory; - } - - public DefaultBHttpClientConnectionFactory( - final ConnectionConfig cconfig, - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory) { - this(cconfig, null, null, requestWriterFactory, responseParserFactory); - } - - public DefaultBHttpClientConnectionFactory(final ConnectionConfig cconfig) { - this(cconfig, null, null, null, null); - } - - public DefaultBHttpClientConnectionFactory() { - this(null, null, null, null, null); - } - - public DefaultBHttpClientConnection createConnection(final Socket socket) throws IOException { - final DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection( - this.cconfig.getBufferSize(), - this.cconfig.getFragmentSizeHint(), - ConnSupport.createDecoder(this.cconfig), - ConnSupport.createEncoder(this.cconfig), - this.cconfig.getMessageConstraints(), - this.incomingContentStrategy, - this.outgoingContentStrategy, - this.requestWriterFactory, - this.responseParserFactory); - conn.bind(socket); - return conn; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultBHttpServerConnection.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultBHttpServerConnection.java deleted file mode 100644 index e4848387..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultBHttpServerConnection.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl; - -import java.io.IOException; -import java.io.OutputStream; -import java.net.Socket; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.HttpServerConnection; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.config.MessageConstraints; -import org.apache.http.entity.ContentLengthStrategy; -import org.apache.http.impl.entity.DisallowIdentityContentLengthStrategy; -import org.apache.http.impl.io.DefaultHttpRequestParserFactory; -import org.apache.http.impl.io.DefaultHttpResponseWriterFactory; -import org.apache.http.io.HttpMessageParser; -import org.apache.http.io.HttpMessageParserFactory; -import org.apache.http.io.HttpMessageWriter; -import org.apache.http.io.HttpMessageWriterFactory; -import org.apache.http.util.Args; - -/** - * Default implementation of {@link HttpServerConnection}. - * - * @since 4.3 - */ -@NotThreadSafe -public class DefaultBHttpServerConnection extends BHttpConnectionBase - implements HttpServerConnection { - - private final HttpMessageParser requestParser; - private final HttpMessageWriter responseWriter; - - /** - * Creates new instance of DefaultBHttpServerConnection. - * - * @param buffersize buffer size. Must be a positive number. - * @param fragmentSizeHint fragment size hint. - * @param chardecoder decoder to be used for decoding HTTP protocol elements. - * If null simple type cast will be used for byte to char conversion. - * @param charencoder encoder to be used for encoding HTTP protocol elements. - * If null simple type cast will be used for char to byte conversion. - * @param constraints Message constraints. If null - * {@link MessageConstraints#DEFAULT} will be used. - * @param incomingContentStrategy incoming content length strategy. If null - * {@link DisallowIdentityContentLengthStrategy#INSTANCE} will be used. - * @param outgoingContentStrategy outgoing content length strategy. If null - * {@link org.apache.http.impl.entity.StrictContentLengthStrategyHC4#INSTANCE} will be used. - * @param requestParserFactory request parser factory. If null - * {@link DefaultHttpRequestParserFactory#INSTANCE} will be used. - * @param responseWriterFactory response writer factory. If null - * {@link DefaultHttpResponseWriterFactory#INSTANCE} will be used. - */ - public DefaultBHttpServerConnection( - final int buffersize, - final int fragmentSizeHint, - final CharsetDecoder chardecoder, - final CharsetEncoder charencoder, - final MessageConstraints constraints, - final ContentLengthStrategy incomingContentStrategy, - final ContentLengthStrategy outgoingContentStrategy, - final HttpMessageParserFactory requestParserFactory, - final HttpMessageWriterFactory responseWriterFactory) { - super(buffersize, fragmentSizeHint, chardecoder, charencoder, constraints, - incomingContentStrategy != null ? incomingContentStrategy : - DisallowIdentityContentLengthStrategy.INSTANCE, outgoingContentStrategy); - this.requestParser = (requestParserFactory != null ? requestParserFactory : - DefaultHttpRequestParserFactory.INSTANCE).create(getSessionInputBuffer(), constraints); - this.responseWriter = (responseWriterFactory != null ? responseWriterFactory : - DefaultHttpResponseWriterFactory.INSTANCE).create(getSessionOutputBuffer()); - } - - public DefaultBHttpServerConnection( - final int buffersize, - final CharsetDecoder chardecoder, - final CharsetEncoder charencoder, - final MessageConstraints constraints) { - this(buffersize, buffersize, chardecoder, charencoder, constraints, null, null, null, null); - } - - public DefaultBHttpServerConnection(final int buffersize) { - this(buffersize, buffersize, null, null, null, null, null, null, null); - } - - protected void onRequestReceived(final HttpRequest request) { - } - - protected void onResponseSubmitted(final HttpResponse response) { - } - - @Override - public void bind(final Socket socket) throws IOException { - super.bind(socket); - } - - public HttpRequest receiveRequestHeader() - throws HttpException, IOException { - ensureOpen(); - final HttpRequest request = (HttpRequest) this.requestParser.parse(); - onRequestReceived(request); - incrementRequestCount(); - return request; - } - - public void receiveRequestEntity(final HttpEntityEnclosingRequest request) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - ensureOpen(); - final HttpEntity entity = prepareInput(request); - request.setEntity(entity); - } - - public void sendResponseHeader(final HttpResponse response) - throws HttpException, IOException { - Args.notNull(response, "HTTP response"); - ensureOpen(); - this.responseWriter.write(response); - onResponseSubmitted(response); - if (response.getStatusLine().getStatusCode() >= 200) { - incrementResponseCount(); - } - } - - public void sendResponseEntity(final HttpResponse response) - throws HttpException, IOException { - Args.notNull(response, "HTTP response"); - ensureOpen(); - final HttpEntity entity = response.getEntity(); - if (entity == null) { - return; - } - final OutputStream outstream = prepareOutput(response); - entity.writeTo(outstream); - outstream.close(); - } - - public void flush() throws IOException { - ensureOpen(); - doFlush(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultBHttpServerConnectionFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultBHttpServerConnectionFactory.java deleted file mode 100644 index b944b3df..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultBHttpServerConnectionFactory.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl; - -import org.apache.http.HttpConnectionFactory; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.Immutable; -import org.apache.http.config.ConnectionConfig; -import org.apache.http.entity.ContentLengthStrategy; -import org.apache.http.io.HttpMessageParserFactory; -import org.apache.http.io.HttpMessageWriterFactory; - -import java.io.IOException; -import java.net.Socket; - -/** - * Default factory for {@link org.apache.http.HttpServerConnection}s. - * - * @since 4.3 - */ -@Immutable -public class DefaultBHttpServerConnectionFactory - implements HttpConnectionFactory { - - public static final DefaultBHttpServerConnectionFactory INSTANCE = new DefaultBHttpServerConnectionFactory(); - - private final ConnectionConfig cconfig; - private final ContentLengthStrategy incomingContentStrategy; - private final ContentLengthStrategy outgoingContentStrategy; - private final HttpMessageParserFactory requestParserFactory; - private final HttpMessageWriterFactory responseWriterFactory; - - public DefaultBHttpServerConnectionFactory( - final ConnectionConfig cconfig, - final ContentLengthStrategy incomingContentStrategy, - final ContentLengthStrategy outgoingContentStrategy, - final HttpMessageParserFactory requestParserFactory, - final HttpMessageWriterFactory responseWriterFactory) { - super(); - this.cconfig = cconfig != null ? cconfig : ConnectionConfig.DEFAULT; - this.incomingContentStrategy = incomingContentStrategy; - this.outgoingContentStrategy = outgoingContentStrategy; - this.requestParserFactory = requestParserFactory; - this.responseWriterFactory = responseWriterFactory; - } - - public DefaultBHttpServerConnectionFactory( - final ConnectionConfig cconfig, - final HttpMessageParserFactory requestParserFactory, - final HttpMessageWriterFactory responseWriterFactory) { - this(cconfig, null, null, requestParserFactory, responseWriterFactory); - } - - public DefaultBHttpServerConnectionFactory(final ConnectionConfig cconfig) { - this(cconfig, null, null, null, null); - } - - public DefaultBHttpServerConnectionFactory() { - this(null, null, null, null, null); - } - - public DefaultBHttpServerConnection createConnection(final Socket socket) throws IOException { - final DefaultBHttpServerConnection conn = new DefaultBHttpServerConnection( - this.cconfig.getBufferSize(), - this.cconfig.getFragmentSizeHint(), - ConnSupport.createDecoder(this.cconfig), - ConnSupport.createEncoder(this.cconfig), - this.cconfig.getMessageConstraints(), - this.incomingContentStrategy, - this.outgoingContentStrategy, - this.requestParserFactory, - this.responseWriterFactory); - conn.bind(socket); - return conn; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultConnectionReuseStrategyHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultConnectionReuseStrategyHC4.java deleted file mode 100644 index bcdd1000..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultConnectionReuseStrategyHC4.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl; - -import org.apache.http.ConnectionReuseStrategy; -import org.apache.http.Header; -import org.apache.http.HeaderIterator; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.HttpVersion; -import org.apache.http.ParseException; -import org.apache.http.ProtocolVersion; -import org.apache.http.TokenIterator; -import org.apache.http.annotation.Immutable; -import org.apache.http.message.BasicTokenIterator; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; - -/** - * Default implementation of a strategy deciding about connection re-use. - * The default implementation first checks some basics, for example - * whether the connection is still open or whether the end of the - * request entity can be determined without closing the connection. - * If these checks pass, the tokens in the Connection header will - * be examined. In the absence of a Connection header, the - * non-standard but commonly used Proxy-Connection header takes - * it's role. A token close indicates that the connection cannot - * be reused. If there is no such token, a token keep-alive - * indicates that the connection should be re-used. If neither token is found, - * or if there are no Connection headers, the default policy for - * the HTTP version is applied. Since HTTP/1.1, connections are - * re-used by default. Up until HTTP/1.0, connections are not - * re-used by default. - * - * @since 4.0 - */ -@Immutable -public class DefaultConnectionReuseStrategyHC4 implements ConnectionReuseStrategy { - - public static final DefaultConnectionReuseStrategyHC4 INSTANCE = new DefaultConnectionReuseStrategyHC4(); - - public DefaultConnectionReuseStrategyHC4() { - super(); - } - - // see interface ConnectionReuseStrategy - public boolean keepAlive(final HttpResponse response, - final HttpContext context) { - Args.notNull(response, "HTTP response"); - Args.notNull(context, "HTTP context"); - - // Check for a self-terminating entity. If the end of the entity will - // be indicated by closing the connection, there is no keep-alive. - final ProtocolVersion ver = response.getStatusLine().getProtocolVersion(); - final Header teh = response.getFirstHeader(HTTP.TRANSFER_ENCODING); - if (teh != null) { - if (!HTTP.CHUNK_CODING.equalsIgnoreCase(teh.getValue())) { - return false; - } - } else { - if (canResponseHaveBody(response)) { - final Header[] clhs = response.getHeaders(HTTP.CONTENT_LEN); - // Do not reuse if not properly content-length delimited - if (clhs.length == 1) { - final Header clh = clhs[0]; - try { - final int contentLen = Integer.parseInt(clh.getValue()); - if (contentLen < 0) { - return false; - } - } catch (final NumberFormatException ex) { - return false; - } - } else { - return false; - } - } - } - - // Check for the "Connection" header. If that is absent, check for - // the "Proxy-Connection" header. The latter is an unspecified and - // broken but unfortunately common extension of HTTP. - HeaderIterator hit = response.headerIterator(HTTP.CONN_DIRECTIVE); - if (!hit.hasNext()) { - hit = response.headerIterator("Proxy-Connection"); - } - - // Experimental usage of the "Connection" header in HTTP/1.0 is - // documented in RFC 2068, section 19.7.1. A token "keep-alive" is - // used to indicate that the connection should be persistent. - // Note that the final specification of HTTP/1.1 in RFC 2616 does not - // include this information. Neither is the "Connection" header - // mentioned in RFC 1945, which informally describes HTTP/1.0. - // - // RFC 2616 specifies "close" as the only connection token with a - // specific meaning: it disables persistent connections. - // - // The "Proxy-Connection" header is not formally specified anywhere, - // but is commonly used to carry one token, "close" or "keep-alive". - // The "Connection" header, on the other hand, is defined as a - // sequence of tokens, where each token is a header name, and the - // token "close" has the above-mentioned additional meaning. - // - // To get through this mess, we treat the "Proxy-Connection" header - // in exactly the same way as the "Connection" header, but only if - // the latter is missing. We scan the sequence of tokens for both - // "close" and "keep-alive". As "close" is specified by RFC 2068, - // it takes precedence and indicates a non-persistent connection. - // If there is no "close" but a "keep-alive", we take the hint. - - if (hit.hasNext()) { - try { - final TokenIterator ti = createTokenIterator(hit); - boolean keepalive = false; - while (ti.hasNext()) { - final String token = ti.nextToken(); - if (HTTP.CONN_CLOSE.equalsIgnoreCase(token)) { - return false; - } else if (HTTP.CONN_KEEP_ALIVE.equalsIgnoreCase(token)) { - // continue the loop, there may be a "close" afterwards - keepalive = true; - } - } - if (keepalive) - { - return true; - // neither "close" nor "keep-alive", use default policy - } - - } catch (final ParseException px) { - // invalid connection header means no persistent connection - // we don't have logging in HttpCore, so the exception is lost - return false; - } - } - - // default since HTTP/1.1 is persistent, before it was non-persistent - return !ver.lessEquals(HttpVersion.HTTP_1_0); - } - - - /** - * Creates a token iterator from a header iterator. - * This method can be overridden to replace the implementation of - * the token iterator. - * - * @param hit the header iterator - * - * @return the token iterator - */ - protected TokenIterator createTokenIterator(final HeaderIterator hit) { - return new BasicTokenIterator(hit); - } - - private boolean canResponseHaveBody(final HttpResponse response) { - final int status = response.getStatusLine().getStatusCode(); - return status >= HttpStatus.SC_OK - && status != HttpStatus.SC_NO_CONTENT - && status != HttpStatus.SC_NOT_MODIFIED - && status != HttpStatus.SC_RESET_CONTENT; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultHttpRequestFactoryHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultHttpRequestFactoryHC4.java deleted file mode 100644 index f502d972..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultHttpRequestFactoryHC4.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl; - -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestFactory; -import org.apache.http.MethodNotSupportedException; -import org.apache.http.RequestLine; -import org.apache.http.annotation.Immutable; -import org.apache.http.message.BasicHttpEntityEnclosingRequest; -import org.apache.http.message.BasicHttpRequest; -import org.apache.http.util.Args; - -/** - * Default factory for creating {@link HttpRequest} objects. - * - * @since 4.0 - */ -@Immutable -public class DefaultHttpRequestFactoryHC4 implements HttpRequestFactory { - - public static final DefaultHttpRequestFactoryHC4 INSTANCE = new DefaultHttpRequestFactoryHC4(); - - private static final String[] RFC2616_COMMON_METHODS = { - "GET" - }; - - private static final String[] RFC2616_ENTITY_ENC_METHODS = { - "POST", - "PUT" - }; - - private static final String[] RFC2616_SPECIAL_METHODS = { - "HEAD", - "OPTIONS", - "DELETE", - "TRACE", - "CONNECT" - }; - - - public DefaultHttpRequestFactoryHC4() { - super(); - } - - private static boolean isOneOf(final String[] methods, final String method) { - for (final String method2 : methods) { - if (method2.equalsIgnoreCase(method)) { - return true; - } - } - return false; - } - - public HttpRequest newHttpRequest(final RequestLine requestline) - throws MethodNotSupportedException { - Args.notNull(requestline, "Request line"); - final String method = requestline.getMethod(); - if (isOneOf(RFC2616_COMMON_METHODS, method)) { - return new BasicHttpRequest(requestline); - } else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) { - return new BasicHttpEntityEnclosingRequest(requestline); - } else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) { - return new BasicHttpRequest(requestline); - } else { - throw new MethodNotSupportedException(method + " method not supported"); - } - } - - public HttpRequest newHttpRequest(final String method, final String uri) - throws MethodNotSupportedException { - if (isOneOf(RFC2616_COMMON_METHODS, method)) { - return new BasicHttpRequest(method, uri); - } else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) { - return new BasicHttpEntityEnclosingRequest(method, uri); - } else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) { - return new BasicHttpRequest(method, uri); - } else { - throw new MethodNotSupportedException(method - + " method not supported"); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultHttpResponseFactoryHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultHttpResponseFactoryHC4.java deleted file mode 100644 index a80b12ee..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/DefaultHttpResponseFactoryHC4.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl; - -import java.util.Locale; - -import org.apache.http.HttpResponse; -import org.apache.http.HttpResponseFactory; -import org.apache.http.ProtocolVersion; -import org.apache.http.ReasonPhraseCatalog; -import org.apache.http.StatusLine; -import org.apache.http.annotation.Immutable; -import org.apache.http.message.BasicHttpResponse; -import org.apache.http.message.BasicStatusLine; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; - -/** - * Default factory for creating {@link HttpResponse} objects. - * - * @since 4.0 - */ -@Immutable -public class DefaultHttpResponseFactoryHC4 implements HttpResponseFactory { - - public static final DefaultHttpResponseFactoryHC4 INSTANCE = new DefaultHttpResponseFactoryHC4(); - - /** The catalog for looking up reason phrases. */ - protected final ReasonPhraseCatalog reasonCatalog; - - - /** - * Creates a new response factory with the given catalog. - * - * @param catalog the catalog of reason phrases - */ - public DefaultHttpResponseFactoryHC4(final ReasonPhraseCatalog catalog) { - this.reasonCatalog = Args.notNull(catalog, "Reason phrase catalog"); - } - - /** - * Creates a new response factory with the default catalog. - * The default catalog is {@link EnglishReasonPhraseCatalog}. - */ - public DefaultHttpResponseFactoryHC4() { - this(EnglishReasonPhraseCatalogHC4.INSTANCE); - } - - - // non-javadoc, see interface HttpResponseFactory - public HttpResponse newHttpResponse( - final ProtocolVersion ver, - final int status, - final HttpContext context) { - Args.notNull(ver, "HTTP version"); - final Locale loc = determineLocale(context); - final String reason = this.reasonCatalog.getReason(status, loc); - final StatusLine statusline = new BasicStatusLine(ver, status, reason); - return new BasicHttpResponse(statusline, this.reasonCatalog, loc); - } - - - // non-javadoc, see interface HttpResponseFactory - public HttpResponse newHttpResponse( - final StatusLine statusline, - final HttpContext context) { - Args.notNull(statusline, "Status line"); - return new BasicHttpResponse(statusline, this.reasonCatalog, determineLocale(context)); - } - - /** - * Determines the locale of the response. - * The implementation in this class always returns the default locale. - * - * @param context the context from which to determine the locale, or - * null to use the default locale - * - * @return the locale for the response, never null - */ - protected Locale determineLocale(final HttpContext context) { - return Locale.getDefault(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/EnglishReasonPhraseCatalogHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/EnglishReasonPhraseCatalogHC4.java deleted file mode 100644 index 091111a4..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/EnglishReasonPhraseCatalogHC4.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl; - -import java.util.Locale; - -import org.apache.http.HttpStatus; -import org.apache.http.ReasonPhraseCatalog; -import org.apache.http.annotation.Immutable; -import org.apache.http.util.Args; - -/** - * English reason phrases for HTTP status codes. - * All status codes defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and - * RFC2518 (WebDAV) are supported. - * - * @since 4.0 - */ -@Immutable -public class EnglishReasonPhraseCatalogHC4 implements ReasonPhraseCatalog { - - // static array with english reason phrases defined below - - /** - * The default instance of this catalog. - * This catalog is thread safe, so there typically - * is no need to create other instances. - */ - public final static EnglishReasonPhraseCatalogHC4 INSTANCE = - new EnglishReasonPhraseCatalogHC4(); - - - /** - * Restricted default constructor, for derived classes. - * If you need an instance of this class, use {@link #INSTANCE INSTANCE}. - */ - protected EnglishReasonPhraseCatalogHC4() { - // no body - } - - - /** - * Obtains the reason phrase for a status code. - * - * @param status the status code, in the range 100-599 - * @param loc ignored - * - * @return the reason phrase, or null - */ - public String getReason(final int status, final Locale loc) { - Args.check(status >= 100 && status < 600, "Unknown category for status code " + status); - final int category = status / 100; - final int subcode = status - 100*category; - - String reason = null; - if (REASON_PHRASES[category].length > subcode) { - reason = REASON_PHRASES[category][subcode]; - } - - return reason; - } - - - /** Reason phrases lookup table. */ - private static final String[][] REASON_PHRASES = new String[][]{ - null, - new String[3], // 1xx - new String[8], // 2xx - new String[8], // 3xx - new String[25], // 4xx - new String[8] // 5xx - }; - - - - /** - * Stores the given reason phrase, by status code. - * Helper method to initialize the static lookup table. - * - * @param status the status code for which to define the phrase - * @param reason the reason phrase for this status code - */ - private static void setReason(final int status, final String reason) { - final int category = status / 100; - final int subcode = status - 100*category; - REASON_PHRASES[category][subcode] = reason; - } - - - // ----------------------------------------------------- Static Initializer - - /** Set up status code to "reason phrase" map. */ - static { - // HTTP 1.0 Server status codes -- see RFC 1945 - setReason(HttpStatus.SC_OK, - "OK"); - setReason(HttpStatus.SC_CREATED, - "Created"); - setReason(HttpStatus.SC_ACCEPTED, - "Accepted"); - setReason(HttpStatus.SC_NO_CONTENT, - "No Content"); - setReason(HttpStatus.SC_MOVED_PERMANENTLY, - "Moved Permanently"); - setReason(HttpStatus.SC_MOVED_TEMPORARILY, - "Moved Temporarily"); - setReason(HttpStatus.SC_NOT_MODIFIED, - "Not Modified"); - setReason(HttpStatus.SC_BAD_REQUEST, - "Bad Request"); - setReason(HttpStatus.SC_UNAUTHORIZED, - "Unauthorized"); - setReason(HttpStatus.SC_FORBIDDEN, - "Forbidden"); - setReason(HttpStatus.SC_NOT_FOUND, - "Not Found"); - setReason(HttpStatus.SC_INTERNAL_SERVER_ERROR, - "Internal Server Error"); - setReason(HttpStatus.SC_NOT_IMPLEMENTED, - "Not Implemented"); - setReason(HttpStatus.SC_BAD_GATEWAY, - "Bad Gateway"); - setReason(HttpStatus.SC_SERVICE_UNAVAILABLE, - "Service Unavailable"); - - // HTTP 1.1 Server status codes -- see RFC 2048 - setReason(HttpStatus.SC_CONTINUE, - "Continue"); - setReason(HttpStatus.SC_TEMPORARY_REDIRECT, - "Temporary Redirect"); - setReason(HttpStatus.SC_METHOD_NOT_ALLOWED, - "Method Not Allowed"); - setReason(HttpStatus.SC_CONFLICT, - "Conflict"); - setReason(HttpStatus.SC_PRECONDITION_FAILED, - "Precondition Failed"); - setReason(HttpStatus.SC_REQUEST_TOO_LONG, - "Request Too Long"); - setReason(HttpStatus.SC_REQUEST_URI_TOO_LONG, - "Request-URI Too Long"); - setReason(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE, - "Unsupported Media Type"); - setReason(HttpStatus.SC_MULTIPLE_CHOICES, - "Multiple Choices"); - setReason(HttpStatus.SC_SEE_OTHER, - "See Other"); - setReason(HttpStatus.SC_USE_PROXY, - "Use Proxy"); - setReason(HttpStatus.SC_PAYMENT_REQUIRED, - "Payment Required"); - setReason(HttpStatus.SC_NOT_ACCEPTABLE, - "Not Acceptable"); - setReason(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED, - "Proxy Authentication Required"); - setReason(HttpStatus.SC_REQUEST_TIMEOUT, - "Request Timeout"); - - setReason(HttpStatus.SC_SWITCHING_PROTOCOLS, - "Switching Protocols"); - setReason(HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION, - "Non Authoritative Information"); - setReason(HttpStatus.SC_RESET_CONTENT, - "Reset Content"); - setReason(HttpStatus.SC_PARTIAL_CONTENT, - "Partial Content"); - setReason(HttpStatus.SC_GATEWAY_TIMEOUT, - "Gateway Timeout"); - setReason(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED, - "Http Version Not Supported"); - setReason(HttpStatus.SC_GONE, - "Gone"); - setReason(HttpStatus.SC_LENGTH_REQUIRED, - "Length Required"); - setReason(HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE, - "Requested Range Not Satisfiable"); - setReason(HttpStatus.SC_EXPECTATION_FAILED, - "Expectation Failed"); - - // WebDAV Server-specific status codes - setReason(HttpStatus.SC_PROCESSING, - "Processing"); - setReason(HttpStatus.SC_MULTI_STATUS, - "Multi-Status"); - setReason(HttpStatus.SC_UNPROCESSABLE_ENTITY, - "Unprocessable Entity"); - setReason(HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE, - "Insufficient Space On Resource"); - setReason(HttpStatus.SC_METHOD_FAILURE, - "Method Failure"); - setReason(HttpStatus.SC_LOCKED, - "Locked"); - setReason(HttpStatus.SC_INSUFFICIENT_STORAGE, - "Insufficient Storage"); - setReason(HttpStatus.SC_FAILED_DEPENDENCY, - "Failed Dependency"); - } - - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/NoConnectionReuseStrategyHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/NoConnectionReuseStrategyHC4.java deleted file mode 100644 index 77fbf3c2..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/NoConnectionReuseStrategyHC4.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl; - -import org.apache.http.ConnectionReuseStrategy; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.Immutable; -import org.apache.http.protocol.HttpContext; - -/** - * A strategy that never re-uses a connection. - * - * @since 4.0 - */ -@Immutable -public class NoConnectionReuseStrategyHC4 implements ConnectionReuseStrategy { - - public static final NoConnectionReuseStrategyHC4 INSTANCE = new NoConnectionReuseStrategyHC4(); - - public NoConnectionReuseStrategyHC4() { - super(); - } - - public boolean keepAlive(final HttpResponse response, final HttpContext context) { - return false; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/AuthSchemeBaseHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/AuthSchemeBaseHC4.java deleted file mode 100644 index b9767206..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/AuthSchemeBaseHC4.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.auth; - -import java.util.Locale; - -import org.apache.http.FormattedHeader; -import org.apache.http.Header; -import org.apache.http.HttpRequest; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.auth.AUTH; -import org.apache.http.auth.AuthenticationException; -import org.apache.http.auth.ChallengeState; -import org.apache.http.auth.ContextAwareAuthScheme; -import org.apache.http.auth.Credentials; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * Abstract authentication scheme class that serves as a basis - * for all authentication schemes supported by HttpClient. This class - * defines the generic way of parsing an authentication challenge. It - * does not make any assumptions regarding the format of the challenge - * nor does it impose any specific way of responding to that challenge. - * - * - * @since 4.0 - */ -@NotThreadSafe -public abstract class AuthSchemeBaseHC4 implements ContextAwareAuthScheme { - - private ChallengeState challengeState; - - /** - * Creates an instance of AuthSchemeBase with the given challenge - * state. - * - * @since 4.2 - * - * @deprecated (4.3) do not use. - */ - @Deprecated - public AuthSchemeBaseHC4(final ChallengeState challengeState) { - super(); - this.challengeState = challengeState; - } - - public AuthSchemeBaseHC4() { - super(); - } - - /** - * Processes the given challenge token. Some authentication schemes - * may involve multiple challenge-response exchanges. Such schemes must be able - * to maintain the state information when dealing with sequential challenges - * - * @param header the challenge header - * - * @throws MalformedChallengeException is thrown if the authentication challenge - * is malformed - */ - public void processChallenge(final Header header) throws MalformedChallengeException { - Args.notNull(header, "Header"); - final String authheader = header.getName(); - if (authheader.equalsIgnoreCase(AUTH.WWW_AUTH)) { - this.challengeState = ChallengeState.TARGET; - } else if (authheader.equalsIgnoreCase(AUTH.PROXY_AUTH)) { - this.challengeState = ChallengeState.PROXY; - } else { - throw new MalformedChallengeException("Unexpected header name: " + authheader); - } - - final CharArrayBuffer buffer; - int pos; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - pos = ((FormattedHeader) header).getValuePos(); - } else { - final String s = header.getValue(); - if (s == null) { - throw new MalformedChallengeException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - pos = 0; - } - while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - final int beginIndex = pos; - while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - final int endIndex = pos; - final String s = buffer.substring(beginIndex, endIndex); - if (!s.equalsIgnoreCase(getSchemeName())) { - throw new MalformedChallengeException("Invalid scheme identifier: " + s); - } - - parseChallenge(buffer, pos, buffer.length()); - } - - - @SuppressWarnings("deprecation") - public Header authenticate( - final Credentials credentials, - final HttpRequest request, - final HttpContext context) throws AuthenticationException { - return authenticate(credentials, request); - } - - protected abstract void parseChallenge( - CharArrayBuffer buffer, int beginIndex, int endIndex) throws MalformedChallengeException; - - /** - * Returns true if authenticating against a proxy, false - * otherwise. - */ - public boolean isProxy() { - return this.challengeState != null && this.challengeState == ChallengeState.PROXY; - } - - /** - * Returns {@link ChallengeState} value or null if unchallenged. - * - * @since 4.2 - */ - public ChallengeState getChallengeState() { - return this.challengeState; - } - - @Override - public String toString() { - final String name = getSchemeName(); - if (name != null) { - return name.toUpperCase(Locale.ENGLISH); - } else { - return super.toString(); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/BasicSchemeFactoryHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/BasicSchemeFactoryHC4.java deleted file mode 100644 index 99d6fe32..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/BasicSchemeFactoryHC4.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.auth; - -import java.nio.charset.Charset; - -import org.apache.http.annotation.Immutable; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AuthSchemeFactory; -import org.apache.http.auth.AuthSchemeProvider; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HttpContext; - -/** - * {@link AuthSchemeProvider} implementation that creates and initializes - * {@link BasicScheme} instances. - * - * @since 4.0 - */ -@Immutable -@SuppressWarnings("deprecation") -public class BasicSchemeFactoryHC4 implements AuthSchemeFactory, AuthSchemeProvider { - - private final Charset charset; - - /** - * @since 4.3 - */ - public BasicSchemeFactoryHC4(final Charset charset) { - super(); - this.charset = charset; - } - - public BasicSchemeFactoryHC4() { - this(null); - } - - public AuthScheme newInstance(final HttpParams params) { - return new BasicSchemeHC4(); - } - - public AuthScheme create(final HttpContext context) { - return new BasicSchemeHC4(this.charset); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/BasicSchemeHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/BasicSchemeHC4.java deleted file mode 100644 index 8059b972..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/BasicSchemeHC4.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.auth; - -import java.nio.charset.Charset; - -import android.util.Base64; -import org.apache.http.Consts; -import org.apache.http.Header; -import org.apache.http.HttpRequest; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.auth.AUTH; -import org.apache.http.auth.AuthenticationException; -import org.apache.http.auth.ChallengeState; -import org.apache.http.auth.Credentials; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.message.BufferedHeader; -import org.apache.http.protocol.BasicHttpContextHC4; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; -import org.apache.http.util.EncodingUtils; - -/** - * Basic authentication scheme as defined in RFC 2617. - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicSchemeHC4 extends RFC2617SchemeHC4 { - - /** Whether the basic authentication process is complete */ - private boolean complete; - - /** - * @since 4.3 - */ - public BasicSchemeHC4(final Charset credentialsCharset) { - super(credentialsCharset); - this.complete = false; - } - - /** - * Creates an instance of BasicScheme with the given challenge - * state. - * - * @since 4.2 - * - * @deprecated (4.3) do not use. - */ - @Deprecated - public BasicSchemeHC4(final ChallengeState challengeState) { - super(challengeState); - } - - public BasicSchemeHC4() { - this(Consts.ASCII); - } - - /** - * Returns textual designation of the basic authentication scheme. - * - * @return basic - */ - public String getSchemeName() { - return "basic"; - } - - /** - * Processes the Basic challenge. - * - * @param header the challenge header - * - * @throws MalformedChallengeException is thrown if the authentication challenge - * is malformed - */ - @Override - public void processChallenge( - final Header header) throws MalformedChallengeException { - super.processChallenge(header); - this.complete = true; - } - - /** - * Tests if the Basic authentication process has been completed. - * - * @return true if Basic authorization has been processed, - * false otherwise. - */ - public boolean isComplete() { - return this.complete; - } - - /** - * Returns false. Basic authentication scheme is request based. - * - * @return false. - */ - public boolean isConnectionBased() { - return false; - } - - /** - * @deprecated (4.2) Use {@link org.apache.http.auth.ContextAwareAuthScheme#authenticate( - * Credentials, HttpRequest, org.apache.http.protocol.HttpContext)} - */ - @Deprecated - public Header authenticate( - final Credentials credentials, final HttpRequest request) throws AuthenticationException { - return authenticate(credentials, request, new BasicHttpContextHC4()); - } - - /** - * Produces basic authorization header for the given set of {@link Credentials}. - * - * @param credentials The set of credentials to be used for authentication - * @param request The request being authenticated - * @throws org.apache.http.auth.InvalidCredentialsException if authentication - * credentials are not valid or not applicable for this authentication scheme - * @throws AuthenticationException if authorization string cannot - * be generated due to an authentication failure - * - * @return a basic authorization string - */ - @Override - public Header authenticate( - final Credentials credentials, - final HttpRequest request, - final HttpContext context) throws AuthenticationException { - - Args.notNull(credentials, "Credentials"); - Args.notNull(request, "HTTP request"); - final StringBuilder tmp = new StringBuilder(); - tmp.append(credentials.getUserPrincipal().getName()); - tmp.append(":"); - tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword()); - - final byte[] base64password = Base64.encode( - EncodingUtils.getBytes(tmp.toString(), getCredentialsCharset(request)), - Base64.NO_WRAP); - - final CharArrayBuffer buffer = new CharArrayBuffer(32); - if (isProxy()) { - buffer.append(AUTH.PROXY_AUTH_RESP); - } else { - buffer.append(AUTH.WWW_AUTH_RESP); - } - buffer.append(": Basic "); - buffer.append(base64password, 0, base64password.length); - - return new BufferedHeader(buffer); - } - - /** - * Returns a basic Authorization header value for the given - * {@link Credentials} and charset. - * - * @param credentials The credentials to encode. - * @param charset The charset to use for encoding the credentials - * - * @return a basic authorization header - * - * @deprecated (4.3) use {@link #authenticate(Credentials, HttpRequest, HttpContext)}. - */ - @Deprecated - public static Header authenticate( - final Credentials credentials, - final String charset, - final boolean proxy) { - Args.notNull(credentials, "Credentials"); - Args.notNull(charset, "charset"); - - final StringBuilder tmp = new StringBuilder(); - tmp.append(credentials.getUserPrincipal().getName()); - tmp.append(":"); - tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword()); - - final byte[] base64password = Base64.encode( - EncodingUtils.getBytes(tmp.toString(), charset), - Base64.NO_WRAP); - - final CharArrayBuffer buffer = new CharArrayBuffer(32); - if (proxy) { - buffer.append(AUTH.PROXY_AUTH_RESP); - } else { - buffer.append(AUTH.WWW_AUTH_RESP); - } - buffer.append(": Basic "); - buffer.append(base64password, 0, base64password.length); - - return new BufferedHeader(buffer); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/DigestSchemeFactoryHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/DigestSchemeFactoryHC4.java deleted file mode 100644 index 564d8dfc..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/DigestSchemeFactoryHC4.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.auth; - -import java.nio.charset.Charset; - -import org.apache.http.annotation.Immutable; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AuthSchemeFactory; -import org.apache.http.auth.AuthSchemeProvider; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HttpContext; - -/** - * {@link AuthSchemeProvider} implementation that creates and initializes - * {@link DigestScheme} instances. - * - * @since 4.0 - */ -@Immutable -@SuppressWarnings("deprecation") -public class DigestSchemeFactoryHC4 implements AuthSchemeFactory, AuthSchemeProvider { - - private final Charset charset; - - /** - * @since 4.3 - */ - public DigestSchemeFactoryHC4(final Charset charset) { - super(); - this.charset = charset; - } - - public DigestSchemeFactoryHC4() { - this(null); - } - - public AuthScheme newInstance(final HttpParams params) { - return new DigestSchemeHC4(); - } - - public AuthScheme create(final HttpContext context) { - return new DigestSchemeHC4(this.charset); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/DigestSchemeHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/DigestSchemeHC4.java deleted file mode 100644 index cfd3a56c..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/DigestSchemeHC4.java +++ /dev/null @@ -1,489 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.auth; - -import java.io.IOException; -import java.nio.charset.Charset; -import java.security.MessageDigest; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.Formatter; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.StringTokenizer; - -import org.apache.http.Consts; -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpRequest; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.auth.AUTH; -import org.apache.http.auth.AuthenticationException; -import org.apache.http.auth.ChallengeState; -import org.apache.http.auth.Credentials; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.message.BasicHeaderValueFormatterHC4; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.message.BufferedHeader; -import org.apache.http.protocol.BasicHttpContextHC4; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; -import org.apache.http.util.EncodingUtils; - -/** - * Digest authentication scheme as defined in RFC 2617. - * Both MD5 (default) and MD5-sess are supported. - * Currently only qop=auth or no qop is supported. qop=auth-int - * is unsupported. If auth and auth-int are provided, auth is - * used. - *

    - * Since the digest username is included as clear text in the generated - * Authentication header, the charset of the username must be compatible - * with the HTTP element charset used by the connection. - * - * @since 4.0 - */ -@NotThreadSafe -public class DigestSchemeHC4 extends RFC2617SchemeHC4 { - - /** - * Hexa values used when creating 32 character long digest in HTTP DigestSchemeHC4 - * in case of authentication. - * - * @see #encode(byte[]) - */ - private static final char[] HEXADECIMAL = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', - 'e', 'f' - }; - - /** Whether the digest authentication process is complete */ - private boolean complete; - - private static final int QOP_UNKNOWN = -1; - private static final int QOP_MISSING = 0; - private static final int QOP_AUTH_INT = 1; - private static final int QOP_AUTH = 2; - - private String lastNonce; - private long nounceCount; - private String cnonce; - private String a1; - private String a2; - - /** - * @since 4.3 - */ - public DigestSchemeHC4(final Charset credentialsCharset) { - super(credentialsCharset); - this.complete = false; - } - - /** - * Creates an instance of DigestScheme with the given challenge - * state. - * - * @since 4.2 - * - * @deprecated (4.3) do not use. - */ - @Deprecated - public DigestSchemeHC4(final ChallengeState challengeState) { - super(challengeState); - } - - public DigestSchemeHC4() { - this(Consts.ASCII); - } - - /** - * Processes the Digest challenge. - * - * @param header the challenge header - * - * @throws MalformedChallengeException is thrown if the authentication challenge - * is malformed - */ - @Override - public void processChallenge( - final Header header) throws MalformedChallengeException { - super.processChallenge(header); - this.complete = true; - } - - /** - * Tests if the Digest authentication process has been completed. - * - * @return true if Digest authorization has been processed, - * false otherwise. - */ - public boolean isComplete() { - final String s = getParameter("stale"); - if ("true".equalsIgnoreCase(s)) { - return false; - } else { - return this.complete; - } - } - - /** - * Returns textual designation of the digest authentication scheme. - * - * @return digest - */ - public String getSchemeName() { - return "digest"; - } - - /** - * Returns false. Digest authentication scheme is request based. - * - * @return false. - */ - public boolean isConnectionBased() { - return false; - } - - public void overrideParamter(final String name, final String value) { - getParameters().put(name, value); - } - - /** - * @deprecated (4.2) Use {@link org.apache.http.auth.ContextAwareAuthScheme#authenticate( - * Credentials, HttpRequest, org.apache.http.protocol.HttpContext)} - */ - @Deprecated - public Header authenticate( - final Credentials credentials, final HttpRequest request) throws AuthenticationException { - return authenticate(credentials, request, new BasicHttpContextHC4()); - } - - /** - * Produces a digest authorization string for the given set of - * {@link Credentials}, method name and URI. - * - * @param credentials A set of credentials to be used for athentication - * @param request The request being authenticated - * - * @throws org.apache.http.auth.InvalidCredentialsException if authentication credentials - * are not valid or not applicable for this authentication scheme - * @throws AuthenticationException if authorization string cannot - * be generated due to an authentication failure - * - * @return a digest authorization string - */ - @Override - public Header authenticate( - final Credentials credentials, - final HttpRequest request, - final HttpContext context) throws AuthenticationException { - - Args.notNull(credentials, "Credentials"); - Args.notNull(request, "HTTP request"); - if (getParameter("realm") == null) { - throw new AuthenticationException("missing realm in challenge"); - } - if (getParameter("nonce") == null) { - throw new AuthenticationException("missing nonce in challenge"); - } - // Add method name and request-URI to the parameter map - getParameters().put("methodname", request.getRequestLine().getMethod()); - getParameters().put("uri", request.getRequestLine().getUri()); - final String charset = getParameter("charset"); - if (charset == null) { - getParameters().put("charset", getCredentialsCharset(request)); - } - return createDigestHeader(credentials, request); - } - - private static MessageDigest createMessageDigest( - final String digAlg) throws UnsupportedDigestAlgorithmException { - try { - return MessageDigest.getInstance(digAlg); - } catch (final Exception e) { - throw new UnsupportedDigestAlgorithmException( - "Unsupported algorithm in HTTP Digest authentication: " - + digAlg); - } - } - - /** - * Creates digest-response header as defined in RFC2617. - * - * @param credentials User credentials - * - * @return The digest-response as String. - */ - private Header createDigestHeader( - final Credentials credentials, - final HttpRequest request) throws AuthenticationException { - final String uri = getParameter("uri"); - final String realm = getParameter("realm"); - final String nonce = getParameter("nonce"); - final String opaque = getParameter("opaque"); - final String method = getParameter("methodname"); - String algorithm = getParameter("algorithm"); - // If an algorithm is not specified, default to MD5. - if (algorithm == null) { - algorithm = "MD5"; - } - - final Set qopset = new HashSet(8); - int qop = QOP_UNKNOWN; - final String qoplist = getParameter("qop"); - if (qoplist != null) { - final StringTokenizer tok = new StringTokenizer(qoplist, ","); - while (tok.hasMoreTokens()) { - final String variant = tok.nextToken().trim(); - qopset.add(variant.toLowerCase(Locale.ENGLISH)); - } - if (request instanceof HttpEntityEnclosingRequest && qopset.contains("auth-int")) { - qop = QOP_AUTH_INT; - } else if (qopset.contains("auth")) { - qop = QOP_AUTH; - } - } else { - qop = QOP_MISSING; - } - - if (qop == QOP_UNKNOWN) { - throw new AuthenticationException("None of the qop methods is supported: " + qoplist); - } - - String charset = getParameter("charset"); - if (charset == null) { - charset = "ISO-8859-1"; - } - - String digAlg = algorithm; - if (digAlg.equalsIgnoreCase("MD5-sess")) { - digAlg = "MD5"; - } - - final MessageDigest digester; - try { - digester = createMessageDigest(digAlg); - } catch (final UnsupportedDigestAlgorithmException ex) { - throw new AuthenticationException("Unsuppported digest algorithm: " + digAlg); - } - - final String uname = credentials.getUserPrincipal().getName(); - final String pwd = credentials.getPassword(); - - if (nonce.equals(this.lastNonce)) { - nounceCount++; - } else { - nounceCount = 1; - cnonce = null; - lastNonce = nonce; - } - final StringBuilder sb = new StringBuilder(256); - final Formatter formatter = new Formatter(sb, Locale.US); - formatter.format("%08x", nounceCount); - formatter.close(); - final String nc = sb.toString(); - - if (cnonce == null) { - cnonce = createCnonce(); - } - - a1 = null; - a2 = null; - // 3.2.2.2: Calculating digest - if (algorithm.equalsIgnoreCase("MD5-sess")) { - // H( unq(username-value) ":" unq(realm-value) ":" passwd ) - // ":" unq(nonce-value) - // ":" unq(cnonce-value) - - // calculated one per session - sb.setLength(0); - sb.append(uname).append(':').append(realm).append(':').append(pwd); - final String checksum = encode(digester.digest(EncodingUtils.getBytes(sb.toString(), charset))); - sb.setLength(0); - sb.append(checksum).append(':').append(nonce).append(':').append(cnonce); - a1 = sb.toString(); - } else { - // unq(username-value) ":" unq(realm-value) ":" passwd - sb.setLength(0); - sb.append(uname).append(':').append(realm).append(':').append(pwd); - a1 = sb.toString(); - } - - final String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset))); - - if (qop == QOP_AUTH) { - // Method ":" digest-uri-value - a2 = method + ':' + uri; - } else if (qop == QOP_AUTH_INT) { - // Method ":" digest-uri-value ":" H(entity-body) - HttpEntity entity = null; - if (request instanceof HttpEntityEnclosingRequest) { - entity = ((HttpEntityEnclosingRequest) request).getEntity(); - } - if (entity != null && !entity.isRepeatable()) { - // If the entity is not repeatable, try falling back onto QOP_AUTH - if (qopset.contains("auth")) { - qop = QOP_AUTH; - a2 = method + ':' + uri; - } else { - throw new AuthenticationException("Qop auth-int cannot be used with " + - "a non-repeatable entity"); - } - } else { - final HttpEntityDigester entityDigester = new HttpEntityDigester(digester); - try { - if (entity != null) { - entity.writeTo(entityDigester); - } - entityDigester.close(); - } catch (final IOException ex) { - throw new AuthenticationException("I/O error reading entity content", ex); - } - a2 = method + ':' + uri + ':' + encode(entityDigester.getDigest()); - } - } else { - a2 = method + ':' + uri; - } - - final String hasha2 = encode(digester.digest(EncodingUtils.getBytes(a2, charset))); - - // 3.2.2.1 - - final String digestValue; - if (qop == QOP_MISSING) { - sb.setLength(0); - sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2); - digestValue = sb.toString(); - } else { - sb.setLength(0); - sb.append(hasha1).append(':').append(nonce).append(':').append(nc).append(':') - .append(cnonce).append(':').append(qop == QOP_AUTH_INT ? "auth-int" : "auth") - .append(':').append(hasha2); - digestValue = sb.toString(); - } - - final String digest = encode(digester.digest(EncodingUtils.getAsciiBytes(digestValue))); - - final CharArrayBuffer buffer = new CharArrayBuffer(128); - if (isProxy()) { - buffer.append(AUTH.PROXY_AUTH_RESP); - } else { - buffer.append(AUTH.WWW_AUTH_RESP); - } - buffer.append(": Digest "); - - final List params = new ArrayList(20); - params.add(new BasicNameValuePair("username", uname)); - params.add(new BasicNameValuePair("realm", realm)); - params.add(new BasicNameValuePair("nonce", nonce)); - params.add(new BasicNameValuePair("uri", uri)); - params.add(new BasicNameValuePair("response", digest)); - - if (qop != QOP_MISSING) { - params.add(new BasicNameValuePair("qop", qop == QOP_AUTH_INT ? "auth-int" : "auth")); - params.add(new BasicNameValuePair("nc", nc)); - params.add(new BasicNameValuePair("cnonce", cnonce)); - } - // algorithm cannot be null here - params.add(new BasicNameValuePair("algorithm", algorithm)); - if (opaque != null) { - params.add(new BasicNameValuePair("opaque", opaque)); - } - - for (int i = 0; i < params.size(); i++) { - final BasicNameValuePair param = params.get(i); - if (i > 0) { - buffer.append(", "); - } - final String name = param.getName(); - final boolean noQuotes = ("nc".equals(name) || "qop".equals(name) - || "algorithm".equals(name)); - BasicHeaderValueFormatterHC4.INSTANCE.formatNameValuePair(buffer, param, !noQuotes); - } - return new BufferedHeader(buffer); - } - - String getCnonce() { - return cnonce; - } - - String getA1() { - return a1; - } - - String getA2() { - return a2; - } - - /** - * Encodes the 128 bit (16 bytes) MD5 digest into a 32 characters long - * String according to RFC 2617. - * - * @param binaryData array containing the digest - * @return encoded MD5, or null if encoding failed - */ - static String encode(final byte[] binaryData) { - final int n = binaryData.length; - final char[] buffer = new char[n * 2]; - for (int i = 0; i < n; i++) { - final int low = (binaryData[i] & 0x0f); - final int high = ((binaryData[i] & 0xf0) >> 4); - buffer[i * 2] = HEXADECIMAL[high]; - buffer[(i * 2) + 1] = HEXADECIMAL[low]; - } - - return new String(buffer); - } - - - /** - * Creates a random cnonce value based on the current time. - * - * @return The cnonce value as String. - */ - public static String createCnonce() { - final SecureRandom rnd = new SecureRandom(); - final byte[] tmp = new byte[8]; - rnd.nextBytes(tmp); - return encode(tmp); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("DIGEST [complete=").append(complete) - .append(", nonce=").append(lastNonce) - .append(", nc=").append(nounceCount) - .append("]"); - return builder.toString(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/HttpAuthenticator.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/HttpAuthenticator.java deleted file mode 100644 index 0744c7de..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/HttpAuthenticator.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.auth; - -import java.io.IOException; -import java.util.Locale; -import java.util.Map; -import java.util.Queue; - -import android.util.Log; - -import org.apache.http.Header; -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.auth.AuthOption; -import org.apache.http.auth.AuthProtocolState; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AuthStateHC4; -import org.apache.http.auth.AuthenticationException; -import org.apache.http.auth.ContextAwareAuthScheme; -import org.apache.http.auth.Credentials; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.client.AuthenticationStrategy; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Asserts; - -/** - * @since 4.3 - */ -public class HttpAuthenticator { - - private final static String TAG = "HttpClient"; - - public HttpAuthenticator() { - super(); - } - - public boolean isAuthenticationRequested( - final HttpHost host, - final HttpResponse response, - final AuthenticationStrategy authStrategy, - final AuthStateHC4 authState, - final HttpContext context) { - if (authStrategy.isAuthenticationRequested(host, response, context)) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Authentication required"); - } - if (authState.getState() == AuthProtocolState.SUCCESS) { - authStrategy.authFailed(host, authState.getAuthScheme(), context); - } - return true; - } else { - switch (authState.getState()) { - case CHALLENGED: - case HANDSHAKE: - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Authentication succeeded"); - } - authState.setState(AuthProtocolState.SUCCESS); - authStrategy.authSucceeded(host, authState.getAuthScheme(), context); - break; - case SUCCESS: - break; - default: - authState.setState(AuthProtocolState.UNCHALLENGED); - } - return false; - } - } - - public boolean handleAuthChallenge( - final HttpHost host, - final HttpResponse response, - final AuthenticationStrategy authStrategy, - final AuthStateHC4 authState, - final HttpContext context) { - try { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, host.toHostString() + " requested authentication"); - } - final Map challenges = authStrategy.getChallenges(host, response, context); - if (challenges.isEmpty()) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Response contains no authentication challenges"); - } - return false; - } - - final AuthScheme authScheme = authState.getAuthScheme(); - switch (authState.getState()) { - case FAILURE: - return false; - case SUCCESS: - authState.reset(); - break; - case CHALLENGED: - case HANDSHAKE: - if (authScheme == null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Auth scheme is null"); - } - authStrategy.authFailed(host, null, context); - authState.reset(); - authState.setState(AuthProtocolState.FAILURE); - return false; - } - case UNCHALLENGED: - if (authScheme != null) { - final String id = authScheme.getSchemeName(); - final Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH)); - if (challenge != null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Authorization challenge processed"); - } - authScheme.processChallenge(challenge); - if (authScheme.isComplete()) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Authentication failed"); - } - authStrategy.authFailed(host, authState.getAuthScheme(), context); - authState.reset(); - authState.setState(AuthProtocolState.FAILURE); - return false; - } else { - authState.setState(AuthProtocolState.HANDSHAKE); - return true; - } - } else { - authState.reset(); - // Retry authentication with a different scheme - } - } - } - final Queue authOptions = authStrategy.select(challenges, host, response, context); - if (authOptions != null && !authOptions.isEmpty()) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Selected authentication options: " + authOptions); - } - authState.setState(AuthProtocolState.CHALLENGED); - authState.update(authOptions); - return true; - } else { - return false; - } - } catch (final MalformedChallengeException ex) { - if (Log.isLoggable(TAG, Log.WARN)) { - Log.w(TAG, "Malformed challenge: " + ex.getMessage()); - } - authState.reset(); - return false; - } - } - - public void generateAuthResponse( - final HttpRequest request, - final AuthStateHC4 authState, - final HttpContext context) throws HttpException, IOException { - AuthScheme authScheme = authState.getAuthScheme(); - Credentials creds = authState.getCredentials(); - switch (authState.getState()) { - case FAILURE: - return; - case SUCCESS: - ensureAuthScheme(authScheme); - if (authScheme.isConnectionBased()) { - return; - } - break; - case CHALLENGED: - final Queue authOptions = authState.getAuthOptions(); - if (authOptions != null) { - while (!authOptions.isEmpty()) { - final AuthOption authOption = authOptions.remove(); - authScheme = authOption.getAuthScheme(); - creds = authOption.getCredentials(); - authState.update(authScheme, creds); - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Generating response to an authentication challenge using " - + authScheme.getSchemeName() + " scheme"); - } - try { - final Header header = doAuth(authScheme, creds, request, context); - request.addHeader(header); - break; - } catch (final AuthenticationException ex) { - if (Log.isLoggable(TAG, Log.WARN)) { - Log.w(TAG, authScheme + " authentication error: " + ex.getMessage()); - } - } - } - return; - } else { - ensureAuthScheme(authScheme); - } - } - if (authScheme != null) { - try { - final Header header = doAuth(authScheme, creds, request, context); - request.addHeader(header); - } catch (final AuthenticationException ex) { - if (Log.isLoggable(TAG, Log.ERROR)) { - Log.e(TAG, authScheme + " authentication error: " + ex.getMessage()); - } - } - } - } - - private void ensureAuthScheme(final AuthScheme authScheme) { - Asserts.notNull(authScheme, "Auth scheme"); - } - - @SuppressWarnings("deprecation") - private Header doAuth( - final AuthScheme authScheme, - final Credentials creds, - final HttpRequest request, - final HttpContext context) throws AuthenticationException { - if (authScheme instanceof ContextAwareAuthScheme) { - return ((ContextAwareAuthScheme) authScheme).authenticate(creds, request, context); - } else { - return authScheme.authenticate(creds, request); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/HttpEntityDigester.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/HttpEntityDigester.java deleted file mode 100644 index 08bc2e67..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/HttpEntityDigester.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.auth; - -import java.io.IOException; -import java.io.OutputStream; -import java.security.MessageDigest; - -class HttpEntityDigester extends OutputStream { - - private final MessageDigest digester; - private boolean closed; - private byte[] digest; - - HttpEntityDigester(final MessageDigest digester) { - super(); - this.digester = digester; - this.digester.reset(); - } - - @Override - public void write(final int b) throws IOException { - if (this.closed) { - throw new IOException("Stream has been already closed"); - } - this.digester.update((byte) b); - } - - @Override - public void write(final byte[] b, final int off, final int len) throws IOException { - if (this.closed) { - throw new IOException("Stream has been already closed"); - } - this.digester.update(b, off, len); - } - - @Override - public void close() throws IOException { - if (this.closed) { - return; - } - this.closed = true; - this.digest = this.digester.digest(); - super.close(); - } - - public byte[] getDigest() { - return this.digest; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/NTLMEngineImpl.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/NTLMEngineImpl.java deleted file mode 100644 index 58f0252b..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/NTLMEngineImpl.java +++ /dev/null @@ -1,1671 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.auth; - -import java.io.UnsupportedEncodingException; -import java.security.Key; -import java.security.MessageDigest; -import java.util.Arrays; -import java.util.Locale; - -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; - -import android.util.Base64; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.util.EncodingUtils; - -/** - * Provides an implementation for NTLMv1, NTLMv2, and NTLM2 Session forms of the NTLM - * authentication protocol. - * - * @since 4.1 - */ -@NotThreadSafe -final class NTLMEngineImpl implements NTLMEngine { - - // Flags we use; descriptions according to: - // http://davenport.sourceforge.net/ntlm.html - // and - // http://msdn.microsoft.com/en-us/library/cc236650%28v=prot.20%29.aspx - protected static final int FLAG_REQUEST_UNICODE_ENCODING = 0x00000001; // Unicode string encoding requested - protected static final int FLAG_REQUEST_TARGET = 0x00000004; // Requests target field - protected static final int FLAG_REQUEST_SIGN = 0x00000010; // Requests all messages have a signature attached, in NEGOTIATE message. - protected static final int FLAG_REQUEST_SEAL = 0x00000020; // Request key exchange for message confidentiality in NEGOTIATE message. MUST be used in conjunction with 56BIT. - protected static final int FLAG_REQUEST_LAN_MANAGER_KEY = 0x00000080; // Request Lan Manager key instead of user session key - protected static final int FLAG_REQUEST_NTLMv1 = 0x00000200; // Request NTLMv1 security. MUST be set in NEGOTIATE and CHALLENGE both - protected static final int FLAG_DOMAIN_PRESENT = 0x00001000; // Domain is present in message - protected static final int FLAG_WORKSTATION_PRESENT = 0x00002000; // Workstation is present in message - protected static final int FLAG_REQUEST_ALWAYS_SIGN = 0x00008000; // Requests a signature block on all messages. Overridden by REQUEST_SIGN and REQUEST_SEAL. - protected static final int FLAG_REQUEST_NTLM2_SESSION = 0x00080000; // From server in challenge, requesting NTLM2 session security - protected static final int FLAG_REQUEST_VERSION = 0x02000000; // Request protocol version - protected static final int FLAG_TARGETINFO_PRESENT = 0x00800000; // From server in challenge message, indicating targetinfo is present - protected static final int FLAG_REQUEST_128BIT_KEY_EXCH = 0x20000000; // Request explicit 128-bit key exchange - protected static final int FLAG_REQUEST_EXPLICIT_KEY_EXCH = 0x40000000; // Request explicit key exchange - protected static final int FLAG_REQUEST_56BIT_ENCRYPTION = 0x80000000; // Must be used in conjunction with SEAL - - - /** Secure random generator */ - private static final java.security.SecureRandom RND_GEN; - static { - java.security.SecureRandom rnd = null; - try { - rnd = java.security.SecureRandom.getInstance("SHA1PRNG"); - } catch (final Exception ignore) { - } - RND_GEN = rnd; - } - - /** Character encoding */ - static final String DEFAULT_CHARSET = "ASCII"; - - /** The character set to use for encoding the credentials */ - private String credentialCharset = DEFAULT_CHARSET; - - /** The signature string as bytes in the default encoding */ - private static final byte[] SIGNATURE; - - static { - final byte[] bytesWithoutNull = EncodingUtils.getBytes("NTLMSSP", "ASCII"); - SIGNATURE = new byte[bytesWithoutNull.length + 1]; - System.arraycopy(bytesWithoutNull, 0, SIGNATURE, 0, bytesWithoutNull.length); - SIGNATURE[bytesWithoutNull.length] = (byte) 0x00; - } - - /** - * Returns the response for the given message. - * - * @param message - * the message that was received from the server. - * @param username - * the username to authenticate with. - * @param password - * the password to authenticate with. - * @param host - * The host. - * @param domain - * the NT domain to authenticate in. - * @return The response. - * @throws org.apache.http.HttpException - * If the messages cannot be retrieved. - */ - final String getResponseFor(final String message, final String username, final String password, - final String host, final String domain) throws NTLMEngineException { - - final String response; - if (message == null || message.trim().equals("")) { - response = getType1Message(host, domain); - } else { - final Type2Message t2m = new Type2Message(message); - response = getType3Message(username, password, host, domain, t2m.getChallenge(), t2m - .getFlags(), t2m.getTarget(), t2m.getTargetInfo()); - } - return response; - } - - /** - * Creates the first message (type 1 message) in the NTLM authentication - * sequence. This message includes the user name, domain and host for the - * authentication session. - * - * @param host - * the computer name of the host requesting authentication. - * @param domain - * The domain to authenticate with. - * @return String the message to add to the HTTP request header. - */ - String getType1Message(final String host, final String domain) throws NTLMEngineException { - return new Type1Message(domain, host).getResponse(); - } - - /** - * Creates the type 3 message using the given server nonce. The type 3 - * message includes all the information for authentication, host, domain, - * username and the result of encrypting the nonce sent by the server using - * the user's password as the key. - * - * @param user - * The user name. This should not include the domain name. - * @param password - * The password. - * @param host - * The host that is originating the authentication request. - * @param domain - * The domain to authenticate within. - * @param nonce - * the 8 byte array the server sent. - * @return The type 3 message. - * @throws NTLMEngineException - * If {@link #RC4(byte[],byte[])} fails. - */ - String getType3Message(final String user, final String password, final String host, final String domain, - final byte[] nonce, final int type2Flags, final String target, final byte[] targetInformation) - throws NTLMEngineException { - return new Type3Message(domain, host, user, password, nonce, type2Flags, target, - targetInformation).getResponse(); - } - - /** - * @return Returns the credentialCharset. - */ - String getCredentialCharset() { - return credentialCharset; - } - - /** - * @param credentialCharset - * The credentialCharset to set. - */ - void setCredentialCharset(final String credentialCharset) { - this.credentialCharset = credentialCharset; - } - - /** Strip dot suffix from a name */ - private static String stripDotSuffix(final String value) { - if (value == null) { - return null; - } - final int index = value.indexOf("."); - if (index != -1) { - return value.substring(0, index); - } - return value; - } - - /** Convert host to standard form */ - private static String convertHost(final String host) { - return stripDotSuffix(host); - } - - /** Convert domain to standard form */ - private static String convertDomain(final String domain) { - return stripDotSuffix(domain); - } - - private static int readULong(final byte[] src, final int index) throws NTLMEngineException { - if (src.length < index + 4) { - throw new NTLMEngineException("NTLM authentication - buffer too small for DWORD"); - } - return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8) - | ((src[index + 2] & 0xff) << 16) | ((src[index + 3] & 0xff) << 24); - } - - private static int readUShort(final byte[] src, final int index) throws NTLMEngineException { - if (src.length < index + 2) { - throw new NTLMEngineException("NTLM authentication - buffer too small for WORD"); - } - return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8); - } - - private static byte[] readSecurityBuffer(final byte[] src, final int index) throws NTLMEngineException { - final int length = readUShort(src, index); - final int offset = readULong(src, index + 4); - if (src.length < offset + length) { - throw new NTLMEngineException( - "NTLM authentication - buffer too small for data item"); - } - final byte[] buffer = new byte[length]; - System.arraycopy(src, offset, buffer, 0, length); - return buffer; - } - - /** Calculate a challenge block */ - private static byte[] makeRandomChallenge() throws NTLMEngineException { - if (RND_GEN == null) { - throw new NTLMEngineException("Random generator not available"); - } - final byte[] rval = new byte[8]; - synchronized (RND_GEN) { - RND_GEN.nextBytes(rval); - } - return rval; - } - - /** Calculate a 16-byte secondary key */ - private static byte[] makeSecondaryKey() throws NTLMEngineException { - if (RND_GEN == null) { - throw new NTLMEngineException("Random generator not available"); - } - final byte[] rval = new byte[16]; - synchronized (RND_GEN) { - RND_GEN.nextBytes(rval); - } - return rval; - } - - protected static class CipherGen { - - protected final String domain; - protected final String user; - protected final String password; - protected final byte[] challenge; - protected final String target; - protected final byte[] targetInformation; - - // Information we can generate but may be passed in (for testing) - protected byte[] clientChallenge; - protected byte[] clientChallenge2; - protected byte[] secondaryKey; - protected byte[] timestamp; - - // Stuff we always generate - protected byte[] lmHash = null; - protected byte[] lmResponse = null; - protected byte[] ntlmHash = null; - protected byte[] ntlmResponse = null; - protected byte[] ntlmv2Hash = null; - protected byte[] lmv2Hash = null; - protected byte[] lmv2Response = null; - protected byte[] ntlmv2Blob = null; - protected byte[] ntlmv2Response = null; - protected byte[] ntlm2SessionResponse = null; - protected byte[] lm2SessionResponse = null; - protected byte[] lmUserSessionKey = null; - protected byte[] ntlmUserSessionKey = null; - protected byte[] ntlmv2UserSessionKey = null; - protected byte[] ntlm2SessionResponseUserSessionKey = null; - protected byte[] lanManagerSessionKey = null; - - public CipherGen(final String domain, final String user, final String password, - final byte[] challenge, final String target, final byte[] targetInformation, - final byte[] clientChallenge, final byte[] clientChallenge2, - final byte[] secondaryKey, final byte[] timestamp) { - this.domain = domain; - this.target = target; - this.user = user; - this.password = password; - this.challenge = challenge; - this.targetInformation = targetInformation; - this.clientChallenge = clientChallenge; - this.clientChallenge2 = clientChallenge2; - this.secondaryKey = secondaryKey; - this.timestamp = timestamp; - } - - public CipherGen(final String domain, final String user, final String password, - final byte[] challenge, final String target, final byte[] targetInformation) { - this(domain, user, password, challenge, target, targetInformation, null, null, null, null); - } - - /** Calculate and return client challenge */ - public byte[] getClientChallenge() - throws NTLMEngineException { - if (clientChallenge == null) { - clientChallenge = makeRandomChallenge(); - } - return clientChallenge; - } - - /** Calculate and return second client challenge */ - public byte[] getClientChallenge2() - throws NTLMEngineException { - if (clientChallenge2 == null) { - clientChallenge2 = makeRandomChallenge(); - } - return clientChallenge2; - } - - /** Calculate and return random secondary key */ - public byte[] getSecondaryKey() - throws NTLMEngineException { - if (secondaryKey == null) { - secondaryKey = makeSecondaryKey(); - } - return secondaryKey; - } - - /** Calculate and return the LMHash */ - public byte[] getLMHash() - throws NTLMEngineException { - if (lmHash == null) { - lmHash = lmHash(password); - } - return lmHash; - } - - /** Calculate and return the LMResponse */ - public byte[] getLMResponse() - throws NTLMEngineException { - if (lmResponse == null) { - lmResponse = lmResponse(getLMHash(),challenge); - } - return lmResponse; - } - - /** Calculate and return the NTLMHash */ - public byte[] getNTLMHash() - throws NTLMEngineException { - if (ntlmHash == null) { - ntlmHash = ntlmHash(password); - } - return ntlmHash; - } - - /** Calculate and return the NTLMResponse */ - public byte[] getNTLMResponse() - throws NTLMEngineException { - if (ntlmResponse == null) { - ntlmResponse = lmResponse(getNTLMHash(),challenge); - } - return ntlmResponse; - } - - /** Calculate the LMv2 hash */ - public byte[] getLMv2Hash() - throws NTLMEngineException { - if (lmv2Hash == null) { - lmv2Hash = lmv2Hash(domain, user, getNTLMHash()); - } - return lmv2Hash; - } - - /** Calculate the NTLMv2 hash */ - public byte[] getNTLMv2Hash() - throws NTLMEngineException { - if (ntlmv2Hash == null) { - ntlmv2Hash = ntlmv2Hash(domain, user, getNTLMHash()); - } - return ntlmv2Hash; - } - - /** Calculate a timestamp */ - public byte[] getTimestamp() { - if (timestamp == null) { - long time = System.currentTimeMillis(); - time += 11644473600000l; // milliseconds from January 1, 1601 -> epoch. - time *= 10000; // tenths of a microsecond. - // convert to little-endian byte array. - timestamp = new byte[8]; - for (int i = 0; i < 8; i++) { - timestamp[i] = (byte) time; - time >>>= 8; - } - } - return timestamp; - } - - /** Calculate the NTLMv2Blob */ - public byte[] getNTLMv2Blob() - throws NTLMEngineException { - if (ntlmv2Blob == null) { - ntlmv2Blob = createBlob(getClientChallenge2(), targetInformation, getTimestamp()); - } - return ntlmv2Blob; - } - - /** Calculate the NTLMv2Response */ - public byte[] getNTLMv2Response() - throws NTLMEngineException { - if (ntlmv2Response == null) { - ntlmv2Response = lmv2Response(getNTLMv2Hash(),challenge,getNTLMv2Blob()); - } - return ntlmv2Response; - } - - /** Calculate the LMv2Response */ - public byte[] getLMv2Response() - throws NTLMEngineException { - if (lmv2Response == null) { - lmv2Response = lmv2Response(getLMv2Hash(),challenge,getClientChallenge()); - } - return lmv2Response; - } - - /** Get NTLM2SessionResponse */ - public byte[] getNTLM2SessionResponse() - throws NTLMEngineException { - if (ntlm2SessionResponse == null) { - ntlm2SessionResponse = ntlm2SessionResponse(getNTLMHash(),challenge,getClientChallenge()); - } - return ntlm2SessionResponse; - } - - /** Calculate and return LM2 session response */ - public byte[] getLM2SessionResponse() - throws NTLMEngineException { - if (lm2SessionResponse == null) { - final byte[] clChallenge = getClientChallenge(); - lm2SessionResponse = new byte[24]; - System.arraycopy(clChallenge, 0, lm2SessionResponse, 0, clChallenge.length); - Arrays.fill(lm2SessionResponse, clChallenge.length, lm2SessionResponse.length, (byte) 0x00); - } - return lm2SessionResponse; - } - - /** Get LMUserSessionKey */ - public byte[] getLMUserSessionKey() - throws NTLMEngineException { - if (lmUserSessionKey == null) { - lmUserSessionKey = new byte[16]; - System.arraycopy(getLMHash(), 0, lmUserSessionKey, 0, 8); - Arrays.fill(lmUserSessionKey, 8, 16, (byte) 0x00); - } - return lmUserSessionKey; - } - - /** Get NTLMUserSessionKey */ - public byte[] getNTLMUserSessionKey() - throws NTLMEngineException { - if (ntlmUserSessionKey == null) { - final MD4 md4 = new MD4(); - md4.update(getNTLMHash()); - ntlmUserSessionKey = md4.getOutput(); - } - return ntlmUserSessionKey; - } - - /** GetNTLMv2UserSessionKey */ - public byte[] getNTLMv2UserSessionKey() - throws NTLMEngineException { - if (ntlmv2UserSessionKey == null) { - final byte[] ntlmv2hash = getNTLMv2Hash(); - final byte[] truncatedResponse = new byte[16]; - System.arraycopy(getNTLMv2Response(), 0, truncatedResponse, 0, 16); - ntlmv2UserSessionKey = hmacMD5(truncatedResponse, ntlmv2hash); - } - return ntlmv2UserSessionKey; - } - - /** Get NTLM2SessionResponseUserSessionKey */ - public byte[] getNTLM2SessionResponseUserSessionKey() - throws NTLMEngineException { - if (ntlm2SessionResponseUserSessionKey == null) { - final byte[] ntlm2SessionResponseNonce = getLM2SessionResponse(); - final byte[] sessionNonce = new byte[challenge.length + ntlm2SessionResponseNonce.length]; - System.arraycopy(challenge, 0, sessionNonce, 0, challenge.length); - System.arraycopy(ntlm2SessionResponseNonce, 0, sessionNonce, challenge.length, ntlm2SessionResponseNonce.length); - ntlm2SessionResponseUserSessionKey = hmacMD5(sessionNonce,getNTLMUserSessionKey()); - } - return ntlm2SessionResponseUserSessionKey; - } - - /** Get LAN Manager session key */ - public byte[] getLanManagerSessionKey() - throws NTLMEngineException { - if (lanManagerSessionKey == null) { - try { - final byte[] keyBytes = new byte[14]; - System.arraycopy(getLMHash(), 0, keyBytes, 0, 8); - Arrays.fill(keyBytes, 8, keyBytes.length, (byte)0xbd); - final Key lowKey = createDESKey(keyBytes, 0); - final Key highKey = createDESKey(keyBytes, 7); - final byte[] truncatedResponse = new byte[8]; - System.arraycopy(getLMResponse(), 0, truncatedResponse, 0, truncatedResponse.length); - Cipher des = Cipher.getInstance("DES/ECB/NoPadding"); - des.init(Cipher.ENCRYPT_MODE, lowKey); - final byte[] lowPart = des.doFinal(truncatedResponse); - des = Cipher.getInstance("DES/ECB/NoPadding"); - des.init(Cipher.ENCRYPT_MODE, highKey); - final byte[] highPart = des.doFinal(truncatedResponse); - lanManagerSessionKey = new byte[16]; - System.arraycopy(lowPart, 0, lanManagerSessionKey, 0, lowPart.length); - System.arraycopy(highPart, 0, lanManagerSessionKey, lowPart.length, highPart.length); - } catch (final Exception e) { - throw new NTLMEngineException(e.getMessage(), e); - } - } - return lanManagerSessionKey; - } - } - - /** Calculates HMAC-MD5 */ - static byte[] hmacMD5(final byte[] value, final byte[] key) - throws NTLMEngineException { - final HMACMD5 hmacMD5 = new HMACMD5(key); - hmacMD5.update(value); - return hmacMD5.getOutput(); - } - - /** Calculates RC4 */ - static byte[] RC4(final byte[] value, final byte[] key) - throws NTLMEngineException { - try { - final Cipher rc4 = Cipher.getInstance("RC4"); - rc4.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "RC4")); - return rc4.doFinal(value); - } catch (final Exception e) { - throw new NTLMEngineException(e.getMessage(), e); - } - } - - /** - * Calculates the NTLM2 Session Response for the given challenge, using the - * specified password and client challenge. - * - * @return The NTLM2 Session Response. This is placed in the NTLM response - * field of the Type 3 message; the LM response field contains the - * client challenge, null-padded to 24 bytes. - */ - static byte[] ntlm2SessionResponse(final byte[] ntlmHash, final byte[] challenge, - final byte[] clientChallenge) throws NTLMEngineException { - try { - // 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 - // algorithm (finally) - // Class x = Class.forName("gnu.crypto.hash.MD5"); - // Method updateMethod = x.getMethod("update",new - // Class[]{byte[].class}); - // Method digestMethod = x.getMethod("digest",new Class[0]); - // Object mdInstance = x.newInstance(); - // updateMethod.invoke(mdInstance,new Object[]{challenge}); - // updateMethod.invoke(mdInstance,new Object[]{clientChallenge}); - // byte[] digest = (byte[])digestMethod.invoke(mdInstance,new - // Object[0]); - - final MessageDigest md5 = MessageDigest.getInstance("MD5"); - md5.update(challenge); - md5.update(clientChallenge); - final byte[] digest = md5.digest(); - - final byte[] sessionHash = new byte[8]; - System.arraycopy(digest, 0, sessionHash, 0, 8); - return lmResponse(ntlmHash, sessionHash); - } catch (final Exception e) { - if (e instanceof NTLMEngineException) { - throw (NTLMEngineException) e; - } - throw new NTLMEngineException(e.getMessage(), e); - } - } - - /** - * Creates the LM Hash of the user's password. - * - * @param password - * The password. - * - * @return The LM Hash of the given password, used in the calculation of the - * LM Response. - */ - private static byte[] lmHash(final String password) throws NTLMEngineException { - try { - final byte[] oemPassword = password.toUpperCase(Locale.ENGLISH).getBytes("US-ASCII"); - final int length = Math.min(oemPassword.length, 14); - final byte[] keyBytes = new byte[14]; - System.arraycopy(oemPassword, 0, keyBytes, 0, length); - final Key lowKey = createDESKey(keyBytes, 0); - final Key highKey = createDESKey(keyBytes, 7); - final byte[] magicConstant = "KGS!@#$%".getBytes("US-ASCII"); - final Cipher des = Cipher.getInstance("DES/ECB/NoPadding"); - des.init(Cipher.ENCRYPT_MODE, lowKey); - final byte[] lowHash = des.doFinal(magicConstant); - des.init(Cipher.ENCRYPT_MODE, highKey); - final byte[] highHash = des.doFinal(magicConstant); - final byte[] lmHash = new byte[16]; - System.arraycopy(lowHash, 0, lmHash, 0, 8); - System.arraycopy(highHash, 0, lmHash, 8, 8); - return lmHash; - } catch (final Exception e) { - throw new NTLMEngineException(e.getMessage(), e); - } - } - - /** - * Creates the NTLM Hash of the user's password. - * - * @param password - * The password. - * - * @return The NTLM Hash of the given password, used in the calculation of - * the NTLM Response and the NTLMv2 and LMv2 Hashes. - */ - private static byte[] ntlmHash(final String password) throws NTLMEngineException { - try { - final byte[] unicodePassword = password.getBytes("UnicodeLittleUnmarked"); - final MD4 md4 = new MD4(); - md4.update(unicodePassword); - return md4.getOutput(); - } catch (final UnsupportedEncodingException e) { - throw new NTLMEngineException("Unicode not supported: " + e.getMessage(), e); - } - } - - /** - * Creates the LMv2 Hash of the user's password. - * - * @return The LMv2 Hash, used in the calculation of the NTLMv2 and LMv2 - * Responses. - */ - private static byte[] lmv2Hash(final String domain, final String user, final byte[] ntlmHash) - throws NTLMEngineException { - try { - final HMACMD5 hmacMD5 = new HMACMD5(ntlmHash); - // Upper case username, upper case domain! - hmacMD5.update(user.toUpperCase(Locale.ENGLISH).getBytes("UnicodeLittleUnmarked")); - if (domain != null) { - hmacMD5.update(domain.toUpperCase(Locale.ENGLISH).getBytes("UnicodeLittleUnmarked")); - } - return hmacMD5.getOutput(); - } catch (final UnsupportedEncodingException e) { - throw new NTLMEngineException("Unicode not supported! " + e.getMessage(), e); - } - } - - /** - * Creates the NTLMv2 Hash of the user's password. - * - * @return The NTLMv2 Hash, used in the calculation of the NTLMv2 and LMv2 - * Responses. - */ - private static byte[] ntlmv2Hash(final String domain, final String user, final byte[] ntlmHash) - throws NTLMEngineException { - try { - final HMACMD5 hmacMD5 = new HMACMD5(ntlmHash); - // Upper case username, mixed case target!! - hmacMD5.update(user.toUpperCase(Locale.ENGLISH).getBytes("UnicodeLittleUnmarked")); - if (domain != null) { - hmacMD5.update(domain.getBytes("UnicodeLittleUnmarked")); - } - return hmacMD5.getOutput(); - } catch (final UnsupportedEncodingException e) { - throw new NTLMEngineException("Unicode not supported! " + e.getMessage(), e); - } - } - - /** - * Creates the LM Response from the given hash and Type 2 challenge. - * - * @param hash - * The LM or NTLM Hash. - * @param challenge - * The server challenge from the Type 2 message. - * - * @return The response (either LM or NTLM, depending on the provided hash). - */ - private static byte[] lmResponse(final byte[] hash, final byte[] challenge) throws NTLMEngineException { - try { - final byte[] keyBytes = new byte[21]; - System.arraycopy(hash, 0, keyBytes, 0, 16); - final Key lowKey = createDESKey(keyBytes, 0); - final Key middleKey = createDESKey(keyBytes, 7); - final Key highKey = createDESKey(keyBytes, 14); - final Cipher des = Cipher.getInstance("DES/ECB/NoPadding"); - des.init(Cipher.ENCRYPT_MODE, lowKey); - final byte[] lowResponse = des.doFinal(challenge); - des.init(Cipher.ENCRYPT_MODE, middleKey); - final byte[] middleResponse = des.doFinal(challenge); - des.init(Cipher.ENCRYPT_MODE, highKey); - final byte[] highResponse = des.doFinal(challenge); - final byte[] lmResponse = new byte[24]; - System.arraycopy(lowResponse, 0, lmResponse, 0, 8); - System.arraycopy(middleResponse, 0, lmResponse, 8, 8); - System.arraycopy(highResponse, 0, lmResponse, 16, 8); - return lmResponse; - } catch (final Exception e) { - throw new NTLMEngineException(e.getMessage(), e); - } - } - - /** - * Creates the LMv2 Response from the given hash, client data, and Type 2 - * challenge. - * - * @param hash - * The NTLMv2 Hash. - * @param clientData - * The client data (blob or client challenge). - * @param challenge - * The server challenge from the Type 2 message. - * - * @return The response (either NTLMv2 or LMv2, depending on the client - * data). - */ - private static byte[] lmv2Response(final byte[] hash, final byte[] challenge, final byte[] clientData) - throws NTLMEngineException { - final HMACMD5 hmacMD5 = new HMACMD5(hash); - hmacMD5.update(challenge); - hmacMD5.update(clientData); - final byte[] mac = hmacMD5.getOutput(); - final byte[] lmv2Response = new byte[mac.length + clientData.length]; - System.arraycopy(mac, 0, lmv2Response, 0, mac.length); - System.arraycopy(clientData, 0, lmv2Response, mac.length, clientData.length); - return lmv2Response; - } - - /** - * Creates the NTLMv2 blob from the given target information block and - * client challenge. - * - * @param targetInformation - * The target information block from the Type 2 message. - * @param clientChallenge - * The random 8-byte client challenge. - * - * @return The blob, used in the calculation of the NTLMv2 Response. - */ - private static byte[] createBlob(final byte[] clientChallenge, final byte[] targetInformation, final byte[] timestamp) { - final byte[] blobSignature = new byte[] { (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00 }; - final byte[] reserved = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; - final byte[] unknown1 = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; - final byte[] unknown2 = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; - final byte[] blob = new byte[blobSignature.length + reserved.length + timestamp.length + 8 - + unknown1.length + targetInformation.length + unknown2.length]; - int offset = 0; - System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length); - offset += blobSignature.length; - System.arraycopy(reserved, 0, blob, offset, reserved.length); - offset += reserved.length; - System.arraycopy(timestamp, 0, blob, offset, timestamp.length); - offset += timestamp.length; - System.arraycopy(clientChallenge, 0, blob, offset, 8); - offset += 8; - System.arraycopy(unknown1, 0, blob, offset, unknown1.length); - offset += unknown1.length; - System.arraycopy(targetInformation, 0, blob, offset, targetInformation.length); - offset += targetInformation.length; - System.arraycopy(unknown2, 0, blob, offset, unknown2.length); - offset += unknown2.length; - return blob; - } - - /** - * Creates a DES encryption key from the given key material. - * - * @param bytes - * A byte array containing the DES key material. - * @param offset - * The offset in the given byte array at which the 7-byte key - * material starts. - * - * @return A DES encryption key created from the key material starting at - * the specified offset in the given byte array. - */ - private static Key createDESKey(final byte[] bytes, final int offset) { - final byte[] keyBytes = new byte[7]; - System.arraycopy(bytes, offset, keyBytes, 0, 7); - final byte[] material = new byte[8]; - material[0] = keyBytes[0]; - material[1] = (byte) (keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1); - material[2] = (byte) (keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2); - material[3] = (byte) (keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3); - material[4] = (byte) (keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4); - material[5] = (byte) (keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5); - material[6] = (byte) (keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6); - material[7] = (byte) (keyBytes[6] << 1); - oddParity(material); - return new SecretKeySpec(material, "DES"); - } - - /** - * Applies odd parity to the given byte array. - * - * @param bytes - * The data whose parity bits are to be adjusted for odd parity. - */ - private static void oddParity(final byte[] bytes) { - for (int i = 0; i < bytes.length; i++) { - final byte b = bytes[i]; - final boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^ (b >>> 4) ^ (b >>> 3) - ^ (b >>> 2) ^ (b >>> 1)) & 0x01) == 0; - if (needsParity) { - bytes[i] |= (byte) 0x01; - } else { - bytes[i] &= (byte) 0xfe; - } - } - } - - /** NTLM message generation, base class */ - static class NTLMMessage { - /** The current response */ - private byte[] messageContents = null; - - /** The current output position */ - private int currentOutputPosition = 0; - - /** Constructor to use when message contents are not yet known */ - NTLMMessage() { - } - - /** Constructor to use when message contents are known */ - NTLMMessage(final String messageBody, final int expectedType) throws NTLMEngineException { - messageContents = Base64.decode(EncodingUtils.getBytes(messageBody, DEFAULT_CHARSET), - Base64.NO_WRAP); - // Look for NTLM message - if (messageContents.length < SIGNATURE.length) { - throw new NTLMEngineException("NTLM message decoding error - packet too short"); - } - int i = 0; - while (i < SIGNATURE.length) { - if (messageContents[i] != SIGNATURE[i]) { - throw new NTLMEngineException( - "NTLM message expected - instead got unrecognized bytes"); - } - i++; - } - - // Check to be sure there's a type 2 message indicator next - final int type = readULong(SIGNATURE.length); - if (type != expectedType) { - throw new NTLMEngineException("NTLM type " + Integer.toString(expectedType) - + " message expected - instead got type " + Integer.toString(type)); - } - - currentOutputPosition = messageContents.length; - } - - /** - * Get the length of the signature and flags, so calculations can adjust - * offsets accordingly. - */ - protected int getPreambleLength() { - return SIGNATURE.length + 4; - } - - /** Get the message length */ - protected int getMessageLength() { - return currentOutputPosition; - } - - /** Read a byte from a position within the message buffer */ - protected byte readByte(final int position) throws NTLMEngineException { - if (messageContents.length < position + 1) { - throw new NTLMEngineException("NTLM: Message too short"); - } - return messageContents[position]; - } - - /** Read a bunch of bytes from a position in the message buffer */ - protected void readBytes(final byte[] buffer, final int position) throws NTLMEngineException { - if (messageContents.length < position + buffer.length) { - throw new NTLMEngineException("NTLM: Message too short"); - } - System.arraycopy(messageContents, position, buffer, 0, buffer.length); - } - - /** Read a ushort from a position within the message buffer */ - protected int readUShort(final int position) throws NTLMEngineException { - return NTLMEngineImpl.readUShort(messageContents, position); - } - - /** Read a ulong from a position within the message buffer */ - protected int readULong(final int position) throws NTLMEngineException { - return NTLMEngineImpl.readULong(messageContents, position); - } - - /** Read a security buffer from a position within the message buffer */ - protected byte[] readSecurityBuffer(final int position) throws NTLMEngineException { - return NTLMEngineImpl.readSecurityBuffer(messageContents, position); - } - - /** - * Prepares the object to create a response of the given length. - * - * @param maxlength - * the maximum length of the response to prepare, not - * including the type and the signature (which this method - * adds). - */ - protected void prepareResponse(final int maxlength, final int messageType) { - messageContents = new byte[maxlength]; - currentOutputPosition = 0; - addBytes(SIGNATURE); - addULong(messageType); - } - - /** - * Adds the given byte to the response. - * - * @param b - * the byte to add. - */ - protected void addByte(final byte b) { - messageContents[currentOutputPosition] = b; - currentOutputPosition++; - } - - /** - * Adds the given bytes to the response. - * - * @param bytes - * the bytes to add. - */ - protected void addBytes(final byte[] bytes) { - if (bytes == null) { - return; - } - for (final byte b : bytes) { - messageContents[currentOutputPosition] = b; - currentOutputPosition++; - } - } - - /** Adds a USHORT to the response */ - protected void addUShort(final int value) { - addByte((byte) (value & 0xff)); - addByte((byte) (value >> 8 & 0xff)); - } - - /** Adds a ULong to the response */ - protected void addULong(final int value) { - addByte((byte) (value & 0xff)); - addByte((byte) (value >> 8 & 0xff)); - addByte((byte) (value >> 16 & 0xff)); - addByte((byte) (value >> 24 & 0xff)); - } - - /** - * Returns the response that has been generated after shrinking the - * array if required and base64 encodes the response. - * - * @return The response as above. - */ - String getResponse() { - final byte[] resp; - if (messageContents.length > currentOutputPosition) { - final byte[] tmp = new byte[currentOutputPosition]; - System.arraycopy(messageContents, 0, tmp, 0, currentOutputPosition); - resp = tmp; - } else { - resp = messageContents; - } - return EncodingUtils.getAsciiString(Base64.encode(resp, Base64.NO_WRAP)); - } - - } - - /** Type 1 message assembly class */ - static class Type1Message extends NTLMMessage { - protected byte[] hostBytes; - protected byte[] domainBytes; - - /** Constructor. Include the arguments the message will need */ - Type1Message(final String domain, final String host) throws NTLMEngineException { - super(); - try { - // Strip off domain name from the host! - final String unqualifiedHost = convertHost(host); - // Use only the base domain name! - final String unqualifiedDomain = convertDomain(domain); - - hostBytes = unqualifiedHost != null? unqualifiedHost.getBytes("ASCII") : null; - domainBytes = unqualifiedDomain != null ? unqualifiedDomain - .toUpperCase(Locale.ENGLISH).getBytes("ASCII") : null; - } catch (final UnsupportedEncodingException e) { - throw new NTLMEngineException("Unicode unsupported: " + e.getMessage(), e); - } - } - - /** - * Getting the response involves building the message before returning - * it - */ - @Override - String getResponse() { - // Now, build the message. Calculate its length first, including - // signature or type. - final int finalLength = 32 + 8 /*+ hostBytes.length + domainBytes.length */; - - // Set up the response. This will initialize the signature, message - // type, and flags. - prepareResponse(finalLength, 1); - - // Flags. These are the complete set of flags we support. - addULong( - //FLAG_WORKSTATION_PRESENT | - //FLAG_DOMAIN_PRESENT | - - // Required flags - //FLAG_REQUEST_LAN_MANAGER_KEY | - FLAG_REQUEST_NTLMv1 | - FLAG_REQUEST_NTLM2_SESSION | - - // Protocol version request - FLAG_REQUEST_VERSION | - - // Recommended privacy settings - FLAG_REQUEST_ALWAYS_SIGN | - //FLAG_REQUEST_SEAL | - //FLAG_REQUEST_SIGN | - - // These must be set according to documentation, based on use of SEAL above - FLAG_REQUEST_128BIT_KEY_EXCH | - FLAG_REQUEST_56BIT_ENCRYPTION | - //FLAG_REQUEST_EXPLICIT_KEY_EXCH | - - FLAG_REQUEST_UNICODE_ENCODING); - - // Domain length (two times). - addUShort(/*domainBytes.length*/0); - addUShort(/*domainBytes.length*/0); - - // Domain offset. - addULong(/*hostBytes.length +*/ 32 + 8); - - // Host length (two times). - addUShort(/*hostBytes.length*/0); - addUShort(/*hostBytes.length*/0); - - // Host offset (always 32 + 8). - addULong(32 + 8); - - // Version - addUShort(0x0105); - // Build - addULong(2600); - // NTLM revision - addUShort(0x0f00); - - - // Host (workstation) String. - //addBytes(hostBytes); - - // Domain String. - //addBytes(domainBytes); - - - return super.getResponse(); - } - - } - - /** Type 2 message class */ - static class Type2Message extends NTLMMessage { - protected byte[] challenge; - protected String target; - protected byte[] targetInfo; - protected int flags; - - Type2Message(final String message) throws NTLMEngineException { - super(message, 2); - - // Type 2 message is laid out as follows: - // First 8 bytes: NTLMSSP[0] - // Next 4 bytes: Ulong, value 2 - // Next 8 bytes, starting at offset 12: target field (2 ushort lengths, 1 ulong offset) - // Next 4 bytes, starting at offset 20: Flags, e.g. 0x22890235 - // Next 8 bytes, starting at offset 24: Challenge - // Next 8 bytes, starting at offset 32: ??? (8 bytes of zeros) - // Next 8 bytes, starting at offset 40: targetinfo field (2 ushort lengths, 1 ulong offset) - // Next 2 bytes, major/minor version number (e.g. 0x05 0x02) - // Next 8 bytes, build number - // Next 2 bytes, protocol version number (e.g. 0x00 0x0f) - // Next, various text fields, and a ushort of value 0 at the end - - // Parse out the rest of the info we need from the message - // The nonce is the 8 bytes starting from the byte in position 24. - challenge = new byte[8]; - readBytes(challenge, 24); - - flags = readULong(20); - - if ((flags & FLAG_REQUEST_UNICODE_ENCODING) == 0) { - throw new NTLMEngineException( - "NTLM type 2 message has flags that make no sense: " - + Integer.toString(flags)); - } - - // Do the target! - target = null; - // The TARGET_DESIRED flag is said to not have understood semantics - // in Type2 messages, so use the length of the packet to decide - // how to proceed instead - if (getMessageLength() >= 12 + 8) { - final byte[] bytes = readSecurityBuffer(12); - if (bytes.length != 0) { - try { - target = new String(bytes, "UnicodeLittleUnmarked"); - } catch (final UnsupportedEncodingException e) { - throw new NTLMEngineException(e.getMessage(), e); - } - } - } - - // Do the target info! - targetInfo = null; - // TARGET_DESIRED flag cannot be relied on, so use packet length - if (getMessageLength() >= 40 + 8) { - final byte[] bytes = readSecurityBuffer(40); - if (bytes.length != 0) { - targetInfo = bytes; - } - } - } - - /** Retrieve the challenge */ - byte[] getChallenge() { - return challenge; - } - - /** Retrieve the target */ - String getTarget() { - return target; - } - - /** Retrieve the target info */ - byte[] getTargetInfo() { - return targetInfo; - } - - /** Retrieve the response flags */ - int getFlags() { - return flags; - } - - } - - /** Type 3 message assembly class */ - static class Type3Message extends NTLMMessage { - // Response flags from the type2 message - protected int type2Flags; - - protected byte[] domainBytes; - protected byte[] hostBytes; - protected byte[] userBytes; - - protected byte[] lmResp; - protected byte[] ntResp; - protected byte[] sessionKey; - - - /** Constructor. Pass the arguments we will need */ - Type3Message(final String domain, final String host, final String user, final String password, final byte[] nonce, - final int type2Flags, final String target, final byte[] targetInformation) - throws NTLMEngineException { - // Save the flags - this.type2Flags = type2Flags; - - // Strip off domain name from the host! - final String unqualifiedHost = convertHost(host); - // Use only the base domain name! - final String unqualifiedDomain = convertDomain(domain); - - // Create a cipher generator class. Use domain BEFORE it gets modified! - final CipherGen gen = new CipherGen(unqualifiedDomain, user, password, nonce, target, targetInformation); - - // Use the new code to calculate the responses, including v2 if that - // seems warranted. - byte[] userSessionKey; - try { - // This conditional may not work on Windows Server 2008 R2 and above, where it has not yet - // been tested - if (((type2Flags & FLAG_TARGETINFO_PRESENT) != 0) && - targetInformation != null && target != null) { - // NTLMv2 - ntResp = gen.getNTLMv2Response(); - lmResp = gen.getLMv2Response(); - if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) { - userSessionKey = gen.getLanManagerSessionKey(); - } else { - userSessionKey = gen.getNTLMv2UserSessionKey(); - } - } else { - // NTLMv1 - if ((type2Flags & FLAG_REQUEST_NTLM2_SESSION) != 0) { - // NTLM2 session stuff is requested - ntResp = gen.getNTLM2SessionResponse(); - lmResp = gen.getLM2SessionResponse(); - if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) { - userSessionKey = gen.getLanManagerSessionKey(); - } else { - userSessionKey = gen.getNTLM2SessionResponseUserSessionKey(); - } - } else { - ntResp = gen.getNTLMResponse(); - lmResp = gen.getLMResponse(); - if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) { - userSessionKey = gen.getLanManagerSessionKey(); - } else { - userSessionKey = gen.getNTLMUserSessionKey(); - } - } - } - } catch (final NTLMEngineException e) { - // This likely means we couldn't find the MD4 hash algorithm - - // fail back to just using LM - ntResp = new byte[0]; - lmResp = gen.getLMResponse(); - if ((type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) != 0) { - userSessionKey = gen.getLanManagerSessionKey(); - } else { - userSessionKey = gen.getLMUserSessionKey(); - } - } - - if ((type2Flags & FLAG_REQUEST_SIGN) != 0) { - if ((type2Flags & FLAG_REQUEST_EXPLICIT_KEY_EXCH) != 0) { - sessionKey = RC4(gen.getSecondaryKey(), userSessionKey); - } else { - sessionKey = userSessionKey; - } - } else { - sessionKey = null; - } - - try { - hostBytes = unqualifiedHost != null ? unqualifiedHost - .getBytes("UnicodeLittleUnmarked") : null; - domainBytes = unqualifiedDomain != null ? unqualifiedDomain - .toUpperCase(Locale.ENGLISH).getBytes("UnicodeLittleUnmarked") : null; - userBytes = user.getBytes("UnicodeLittleUnmarked"); - } catch (final UnsupportedEncodingException e) { - throw new NTLMEngineException("Unicode not supported: " + e.getMessage(), e); - } - } - - /** Assemble the response */ - @Override - String getResponse() { - final int ntRespLen = ntResp.length; - final int lmRespLen = lmResp.length; - - final int domainLen = domainBytes != null ? domainBytes.length : 0; - final int hostLen = hostBytes != null ? hostBytes.length: 0; - final int userLen = userBytes.length; - final int sessionKeyLen; - if (sessionKey != null) { - sessionKeyLen = sessionKey.length; - } else { - sessionKeyLen = 0; - } - - // Calculate the layout within the packet - final int lmRespOffset = 72; // allocate space for the version - final int ntRespOffset = lmRespOffset + lmRespLen; - final int domainOffset = ntRespOffset + ntRespLen; - final int userOffset = domainOffset + domainLen; - final int hostOffset = userOffset + userLen; - final int sessionKeyOffset = hostOffset + hostLen; - final int finalLength = sessionKeyOffset + sessionKeyLen; - - // Start the response. Length includes signature and type - prepareResponse(finalLength, 3); - - // LM Resp Length (twice) - addUShort(lmRespLen); - addUShort(lmRespLen); - - // LM Resp Offset - addULong(lmRespOffset); - - // NT Resp Length (twice) - addUShort(ntRespLen); - addUShort(ntRespLen); - - // NT Resp Offset - addULong(ntRespOffset); - - // Domain length (twice) - addUShort(domainLen); - addUShort(domainLen); - - // Domain offset. - addULong(domainOffset); - - // User Length (twice) - addUShort(userLen); - addUShort(userLen); - - // User offset - addULong(userOffset); - - // Host length (twice) - addUShort(hostLen); - addUShort(hostLen); - - // Host offset - addULong(hostOffset); - - // Session key length (twice) - addUShort(sessionKeyLen); - addUShort(sessionKeyLen); - - // Session key offset - addULong(sessionKeyOffset); - - // Flags. - addULong( - //FLAG_WORKSTATION_PRESENT | - //FLAG_DOMAIN_PRESENT | - - // Required flags - (type2Flags & FLAG_REQUEST_LAN_MANAGER_KEY) | - (type2Flags & FLAG_REQUEST_NTLMv1) | - (type2Flags & FLAG_REQUEST_NTLM2_SESSION) | - - // Protocol version request - FLAG_REQUEST_VERSION | - - // Recommended privacy settings - (type2Flags & FLAG_REQUEST_ALWAYS_SIGN) | - (type2Flags & FLAG_REQUEST_SEAL) | - (type2Flags & FLAG_REQUEST_SIGN) | - - // These must be set according to documentation, based on use of SEAL above - (type2Flags & FLAG_REQUEST_128BIT_KEY_EXCH) | - (type2Flags & FLAG_REQUEST_56BIT_ENCRYPTION) | - (type2Flags & FLAG_REQUEST_EXPLICIT_KEY_EXCH) | - - (type2Flags & FLAG_TARGETINFO_PRESENT) | - (type2Flags & FLAG_REQUEST_UNICODE_ENCODING) | - (type2Flags & FLAG_REQUEST_TARGET) - ); - - // Version - addUShort(0x0105); - // Build - addULong(2600); - // NTLM revision - addUShort(0x0f00); - - // Add the actual data - addBytes(lmResp); - addBytes(ntResp); - addBytes(domainBytes); - addBytes(userBytes); - addBytes(hostBytes); - if (sessionKey != null) { - addBytes(sessionKey); - } - - return super.getResponse(); - } - } - - static void writeULong(final byte[] buffer, final int value, final int offset) { - buffer[offset] = (byte) (value & 0xff); - buffer[offset + 1] = (byte) (value >> 8 & 0xff); - buffer[offset + 2] = (byte) (value >> 16 & 0xff); - buffer[offset + 3] = (byte) (value >> 24 & 0xff); - } - - static int F(final int x, final int y, final int z) { - return ((x & y) | (~x & z)); - } - - static int G(final int x, final int y, final int z) { - return ((x & y) | (x & z) | (y & z)); - } - - static int H(final int x, final int y, final int z) { - return (x ^ y ^ z); - } - - static int rotintlft(final int val, final int numbits) { - return ((val << numbits) | (val >>> (32 - numbits))); - } - - /** - * Cryptography support - MD4. The following class was based loosely on the - * RFC and on code found at http://www.cs.umd.edu/~harry/jotp/src/md.java. - * Code correctness was verified by looking at MD4.java from the jcifs - * library (http://jcifs.samba.org). It was massaged extensively to the - * final form found here by Karl Wright (kwright@metacarta.com). - */ - static class MD4 { - protected int A = 0x67452301; - protected int B = 0xefcdab89; - protected int C = 0x98badcfe; - protected int D = 0x10325476; - protected long count = 0L; - protected byte[] dataBuffer = new byte[64]; - - MD4() { - } - - void update(final byte[] input) { - // 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 - // full. - int curBufferPos = (int) (count & 63L); - int inputIndex = 0; - while (input.length - inputIndex + curBufferPos >= dataBuffer.length) { - // We have enough data to do the next step. Do a partial copy - // and a transform, updating inputIndex and curBufferPos - // accordingly - final int transferAmt = dataBuffer.length - curBufferPos; - System.arraycopy(input, inputIndex, dataBuffer, curBufferPos, transferAmt); - count += transferAmt; - curBufferPos = 0; - inputIndex += transferAmt; - processBuffer(); - } - - // If there's anything left, copy it into the buffer and leave it. - // We know there's not enough left to process. - if (inputIndex < input.length) { - final int transferAmt = input.length - inputIndex; - System.arraycopy(input, inputIndex, dataBuffer, curBufferPos, transferAmt); - count += transferAmt; - curBufferPos += transferAmt; - } - } - - byte[] getOutput() { - // Feed pad/length data into engine. This must round out the input - // to a multiple of 512 bits. - final int bufferIndex = (int) (count & 63L); - final int padLen = (bufferIndex < 56) ? (56 - bufferIndex) : (120 - bufferIndex); - final byte[] postBytes = new byte[padLen + 8]; - // Leading 0x80, specified amount of zero padding, then length in - // bits. - postBytes[0] = (byte) 0x80; - // Fill out the last 8 bytes with the length - for (int i = 0; i < 8; i++) { - postBytes[padLen + i] = (byte) ((count * 8) >>> (8 * i)); - } - - // Update the engine - update(postBytes); - - // Calculate final result - final byte[] result = new byte[16]; - writeULong(result, A, 0); - writeULong(result, B, 4); - writeULong(result, C, 8); - writeULong(result, D, 12); - return result; - } - - protected void processBuffer() { - // Convert current buffer to 16 ulongs - final int[] d = new int[16]; - - for (int i = 0; i < 16; i++) { - d[i] = (dataBuffer[i * 4] & 0xff) + ((dataBuffer[i * 4 + 1] & 0xff) << 8) - + ((dataBuffer[i * 4 + 2] & 0xff) << 16) - + ((dataBuffer[i * 4 + 3] & 0xff) << 24); - } - - // Do a round of processing - final int AA = A; - final int BB = B; - final int CC = C; - final int DD = D; - round1(d); - round2(d); - round3(d); - A += AA; - B += BB; - C += CC; - D += DD; - - } - - protected void round1(final int[] d) { - A = rotintlft((A + F(B, C, D) + d[0]), 3); - D = rotintlft((D + F(A, B, C) + d[1]), 7); - C = rotintlft((C + F(D, A, B) + d[2]), 11); - B = rotintlft((B + F(C, D, A) + d[3]), 19); - - A = rotintlft((A + F(B, C, D) + d[4]), 3); - D = rotintlft((D + F(A, B, C) + d[5]), 7); - C = rotintlft((C + F(D, A, B) + d[6]), 11); - B = rotintlft((B + F(C, D, A) + d[7]), 19); - - A = rotintlft((A + F(B, C, D) + d[8]), 3); - D = rotintlft((D + F(A, B, C) + d[9]), 7); - C = rotintlft((C + F(D, A, B) + d[10]), 11); - B = rotintlft((B + F(C, D, A) + d[11]), 19); - - A = rotintlft((A + F(B, C, D) + d[12]), 3); - D = rotintlft((D + F(A, B, C) + d[13]), 7); - C = rotintlft((C + F(D, A, B) + d[14]), 11); - B = rotintlft((B + F(C, D, A) + d[15]), 19); - } - - protected void round2(final int[] d) { - A = rotintlft((A + G(B, C, D) + d[0] + 0x5a827999), 3); - D = rotintlft((D + G(A, B, C) + d[4] + 0x5a827999), 5); - C = rotintlft((C + G(D, A, B) + d[8] + 0x5a827999), 9); - B = rotintlft((B + G(C, D, A) + d[12] + 0x5a827999), 13); - - A = rotintlft((A + G(B, C, D) + d[1] + 0x5a827999), 3); - D = rotintlft((D + G(A, B, C) + d[5] + 0x5a827999), 5); - C = rotintlft((C + G(D, A, B) + d[9] + 0x5a827999), 9); - B = rotintlft((B + G(C, D, A) + d[13] + 0x5a827999), 13); - - A = rotintlft((A + G(B, C, D) + d[2] + 0x5a827999), 3); - D = rotintlft((D + G(A, B, C) + d[6] + 0x5a827999), 5); - C = rotintlft((C + G(D, A, B) + d[10] + 0x5a827999), 9); - B = rotintlft((B + G(C, D, A) + d[14] + 0x5a827999), 13); - - A = rotintlft((A + G(B, C, D) + d[3] + 0x5a827999), 3); - D = rotintlft((D + G(A, B, C) + d[7] + 0x5a827999), 5); - C = rotintlft((C + G(D, A, B) + d[11] + 0x5a827999), 9); - B = rotintlft((B + G(C, D, A) + d[15] + 0x5a827999), 13); - - } - - protected void round3(final int[] d) { - A = rotintlft((A + H(B, C, D) + d[0] + 0x6ed9eba1), 3); - D = rotintlft((D + H(A, B, C) + d[8] + 0x6ed9eba1), 9); - C = rotintlft((C + H(D, A, B) + d[4] + 0x6ed9eba1), 11); - B = rotintlft((B + H(C, D, A) + d[12] + 0x6ed9eba1), 15); - - A = rotintlft((A + H(B, C, D) + d[2] + 0x6ed9eba1), 3); - D = rotintlft((D + H(A, B, C) + d[10] + 0x6ed9eba1), 9); - C = rotintlft((C + H(D, A, B) + d[6] + 0x6ed9eba1), 11); - B = rotintlft((B + H(C, D, A) + d[14] + 0x6ed9eba1), 15); - - A = rotintlft((A + H(B, C, D) + d[1] + 0x6ed9eba1), 3); - D = rotintlft((D + H(A, B, C) + d[9] + 0x6ed9eba1), 9); - C = rotintlft((C + H(D, A, B) + d[5] + 0x6ed9eba1), 11); - B = rotintlft((B + H(C, D, A) + d[13] + 0x6ed9eba1), 15); - - A = rotintlft((A + H(B, C, D) + d[3] + 0x6ed9eba1), 3); - D = rotintlft((D + H(A, B, C) + d[11] + 0x6ed9eba1), 9); - C = rotintlft((C + H(D, A, B) + d[7] + 0x6ed9eba1), 11); - B = rotintlft((B + H(C, D, A) + d[15] + 0x6ed9eba1), 15); - - } - - } - - /** - * Cryptography support - HMACMD5 - algorithmically based on various web - * resources by Karl Wright - */ - static class HMACMD5 { - protected byte[] ipad; - protected byte[] opad; - protected MessageDigest md5; - - HMACMD5(final byte[] input) throws NTLMEngineException { - byte[] key = input; - try { - md5 = MessageDigest.getInstance("MD5"); - } catch (final Exception ex) { - // Umm, the algorithm doesn't exist - throw an - // NTLMEngineException! - throw new NTLMEngineException( - "Error getting md5 message digest implementation: " + ex.getMessage(), ex); - } - - // Initialize the pad buffers with the key - ipad = new byte[64]; - opad = new byte[64]; - - int keyLength = key.length; - if (keyLength > 64) { - // Use MD5 of the key instead, as described in RFC 2104 - md5.update(key); - key = md5.digest(); - keyLength = key.length; - } - int i = 0; - while (i < keyLength) { - ipad[i] = (byte) (key[i] ^ (byte) 0x36); - opad[i] = (byte) (key[i] ^ (byte) 0x5c); - i++; - } - while (i < 64) { - ipad[i] = (byte) 0x36; - opad[i] = (byte) 0x5c; - i++; - } - - // Very important: update the digest with the ipad buffer - md5.reset(); - md5.update(ipad); - - } - - /** Grab the current digest. This is the "answer". */ - byte[] getOutput() { - final byte[] digest = md5.digest(); - md5.update(opad); - return md5.digest(digest); - } - - /** Update by adding a complete array */ - void update(final byte[] input) { - md5.update(input); - } - - /** Update the algorithm */ - void update(final byte[] input, final int offset, final int length) { - md5.update(input, offset, length); - } - - } - - public String generateType1Msg( - final String domain, - final String workstation) throws NTLMEngineException { - return getType1Message(workstation, domain); - } - - public String generateType3Msg( - final String username, - final String password, - final String domain, - final String workstation, - final String challenge) throws NTLMEngineException { - final Type2Message t2m = new Type2Message(challenge); - return getType3Message( - username, - password, - workstation, - domain, - t2m.getChallenge(), - t2m.getFlags(), - t2m.getTarget(), - t2m.getTargetInfo()); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/NTLMSchemeFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/NTLMSchemeFactory.java deleted file mode 100644 index 06e001b0..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/NTLMSchemeFactory.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.auth; - -import org.apache.http.annotation.Immutable; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AuthSchemeFactory; -import org.apache.http.auth.AuthSchemeProvider; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HttpContext; - -/** - * {@link AuthSchemeProvider} implementation that creates and initializes - * {@link NTLMScheme} instances configured to use the default {@link NTLMEngine} - * implementation. - * - * @since 4.1 - */ -@Immutable -@SuppressWarnings("deprecation") -public class NTLMSchemeFactory implements AuthSchemeFactory, AuthSchemeProvider { - - public AuthScheme newInstance(final HttpParams params) { - return new NTLMSchemeHC4(); - } - - public AuthScheme create(final HttpContext context) { - return new NTLMSchemeHC4(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/NTLMSchemeHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/NTLMSchemeHC4.java deleted file mode 100644 index f540392d..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/NTLMSchemeHC4.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.auth; - -import org.apache.http.Header; -import org.apache.http.HttpRequest; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.auth.AUTH; -import org.apache.http.auth.AuthenticationException; -import org.apache.http.auth.Credentials; -import org.apache.http.auth.InvalidCredentialsException; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.auth.NTCredentials; -import org.apache.http.message.BufferedHeader; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * NTLM is a proprietary authentication scheme developed by Microsoft - * and optimized for Windows platforms. - * - * @since 4.0 - */ -@NotThreadSafe -public class NTLMSchemeHC4 extends AuthSchemeBaseHC4 { - - enum State { - UNINITIATED, - CHALLENGE_RECEIVED, - MSG_TYPE1_GENERATED, - MSG_TYPE2_RECEVIED, - MSG_TYPE3_GENERATED, - FAILED, - } - - private final NTLMEngine engine; - - private State state; - private String challenge; - - public NTLMSchemeHC4(final NTLMEngine engine) { - super(); - Args.notNull(engine, "NTLM engine"); - this.engine = engine; - this.state = State.UNINITIATED; - this.challenge = null; - } - - /** - * @since 4.3 - */ - public NTLMSchemeHC4() { - this(new NTLMEngineImpl()); - } - - public String getSchemeName() { - return "ntlm"; - } - - public String getParameter(final String name) { - // String parameters not supported - return null; - } - - public String getRealm() { - // NTLM does not support the concept of an authentication realm - return null; - } - - public boolean isConnectionBased() { - return true; - } - - @Override - protected void parseChallenge( - final CharArrayBuffer buffer, - final int beginIndex, final int endIndex) throws MalformedChallengeException { - this.challenge = buffer.substringTrimmed(beginIndex, endIndex); - if (this.challenge.length() == 0) { - if (this.state == State.UNINITIATED) { - this.state = State.CHALLENGE_RECEIVED; - } else { - this.state = State.FAILED; - } - } else { - if (this.state.compareTo(State.MSG_TYPE1_GENERATED) < 0) { - this.state = State.FAILED; - throw new MalformedChallengeException("Out of sequence NTLM response message"); - } else if (this.state == State.MSG_TYPE1_GENERATED) { - this.state = State.MSG_TYPE2_RECEVIED; - } - } - } - - public Header authenticate( - final Credentials credentials, - final HttpRequest request) throws AuthenticationException { - NTCredentials ntcredentials = null; - try { - ntcredentials = (NTCredentials) credentials; - } catch (final ClassCastException e) { - throw new InvalidCredentialsException( - "Credentials cannot be used for NTLM authentication: " - + credentials.getClass().getName()); - } - String response = null; - if (this.state == State.FAILED) { - throw new AuthenticationException("NTLM authentication failed"); - } else if (this.state == State.CHALLENGE_RECEIVED) { - response = this.engine.generateType1Msg( - ntcredentials.getDomain(), - ntcredentials.getWorkstation()); - this.state = State.MSG_TYPE1_GENERATED; - } else if (this.state == State.MSG_TYPE2_RECEVIED) { - response = this.engine.generateType3Msg( - ntcredentials.getUserName(), - ntcredentials.getPassword(), - ntcredentials.getDomain(), - ntcredentials.getWorkstation(), - this.challenge); - this.state = State.MSG_TYPE3_GENERATED; - } else { - throw new AuthenticationException("Unexpected state: " + this.state); - } - final CharArrayBuffer buffer = new CharArrayBuffer(32); - if (isProxy()) { - buffer.append(AUTH.PROXY_AUTH_RESP); - } else { - buffer.append(AUTH.WWW_AUTH_RESP); - } - buffer.append(": NTLM "); - buffer.append(response); - return new BufferedHeader(buffer); - } - - public boolean isComplete() { - return this.state == State.MSG_TYPE3_GENERATED || this.state == State.FAILED; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/RFC2617SchemeHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/RFC2617SchemeHC4.java deleted file mode 100644 index 4c620606..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/RFC2617SchemeHC4.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.auth; - -import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import org.apache.http.Consts; -import org.apache.http.HeaderElement; -import org.apache.http.HttpRequest; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.auth.ChallengeState; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.auth.params.AuthPNames; -import org.apache.http.message.BasicHeaderValueParserHC4; -import org.apache.http.message.HeaderValueParser; -import org.apache.http.message.ParserCursor; -import org.apache.http.util.CharArrayBuffer; - -/** - * Abstract authentication scheme class that lays foundation for all - * RFC 2617 compliant authentication schemes and provides capabilities common - * to all authentication schemes defined in RFC 2617. - * - * @since 4.0 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe // AuthSchemeBase, params -public abstract class RFC2617SchemeHC4 extends AuthSchemeBaseHC4 { - - private final Map params; - private final Charset credentialsCharset; - - /** - * Creates an instance of RFC2617Scheme with the given challenge - * state. - * - * @since 4.2 - * - * @deprecated (4.3) do not use. - */ - @Deprecated - public RFC2617SchemeHC4(final ChallengeState challengeState) { - super(challengeState); - this.params = new HashMap(); - this.credentialsCharset = Consts.ASCII; - } - - /** - * @since 4.3 - */ - public RFC2617SchemeHC4(final Charset credentialsCharset) { - super(); - this.params = new HashMap(); - this.credentialsCharset = credentialsCharset != null ? credentialsCharset : Consts.ASCII; - } - - public RFC2617SchemeHC4() { - this(Consts.ASCII); - } - - - /** - * @since 4.3 - */ - public Charset getCredentialsCharset() { - return credentialsCharset; - } - - String getCredentialsCharset(final HttpRequest request) { - String charset = (String) request.getParams().getParameter(AuthPNames.CREDENTIAL_CHARSET); - if (charset == null) { - charset = getCredentialsCharset().name(); - } - return charset; - } - - @Override - protected void parseChallenge( - final CharArrayBuffer buffer, final int pos, final int len) throws MalformedChallengeException { - final HeaderValueParser parser = BasicHeaderValueParserHC4.INSTANCE; - final ParserCursor cursor = new ParserCursor(pos, buffer.length()); - final HeaderElement[] elements = parser.parseElements(buffer, cursor); - if (elements.length == 0) { - throw new MalformedChallengeException("Authentication challenge is empty"); - } - this.params.clear(); - for (final HeaderElement element : elements) { - this.params.put(element.getName().toLowerCase(Locale.ENGLISH), element.getValue()); - } - } - - /** - * Returns authentication parameters map. Keys in the map are lower-cased. - * - * @return the map of authentication parameters - */ - protected Map getParameters() { - return this.params; - } - - /** - * Returns authentication parameter with the given name, if available. - * - * @param name The name of the parameter to be returned - * - * @return the parameter with the given name - */ - public String getParameter(final String name) { - if (name == null) { - return null; - } - return this.params.get(name.toLowerCase(Locale.ENGLISH)); - } - - /** - * Returns authentication realm. The realm may not be null. - * - * @return the authentication realm - */ - public String getRealm() { - return getParameter("realm"); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/package-info.java deleted file mode 100644 index 9e50a027..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/auth/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Default implementations of standard and common HTTP authentication - * schemes. - */ -package org.apache.http.impl.auth; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/AIMDBackoffManager.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/AIMDBackoffManager.java deleted file mode 100644 index 2ce22652..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/AIMDBackoffManager.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.client; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.http.client.BackoffManager; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.pool.ConnPoolControl; -import org.apache.http.util.Args; - -/** - *

    The AIMDBackoffManager applies an additive increase, - * multiplicative decrease (AIMD) to managing a dynamic limit to - * the number of connections allowed to a given host. You may want - * to experiment with the settings for the cooldown periods and the - * backoff factor to get the adaptive behavior you want.

    - * - *

    Generally speaking, shorter cooldowns will lead to more steady-state - * variability but faster reaction times, while longer cooldowns - * will lead to more stable equilibrium behavior but slower reaction - * times.

    - * - *

    Similarly, higher backoff factors promote greater - * utilization of available capacity at the expense of fairness - * among clients. Lower backoff factors allow equal distribution of - * capacity among clients (fairness) to happen faster, at the - * expense of having more server capacity unused in the short term.

    - * - * @since 4.2 - */ -public class AIMDBackoffManager implements BackoffManager { - - private final ConnPoolControl connPerRoute; - private final Clock clock; - private final Map lastRouteProbes; - private final Map lastRouteBackoffs; - private long coolDown = 5 * 1000L; - private double backoffFactor = 0.5; - private int cap = 2; // Per RFC 2616 sec 8.1.4 - - /** - * Creates an AIMDBackoffManager to manage - * per-host connection pool sizes represented by the - * given {@link ConnPoolControl}. - * @param connPerRoute per-host routing maximums to - * be managed - */ - public AIMDBackoffManager(final ConnPoolControl connPerRoute) { - this(connPerRoute, new SystemClock()); - } - - AIMDBackoffManager(final ConnPoolControl connPerRoute, final Clock clock) { - this.clock = clock; - this.connPerRoute = connPerRoute; - this.lastRouteProbes = new HashMap(); - this.lastRouteBackoffs = new HashMap(); - } - - public void backOff(final HttpRoute route) { - synchronized(connPerRoute) { - final int curr = connPerRoute.getMaxPerRoute(route); - final Long lastUpdate = getLastUpdate(lastRouteBackoffs, route); - final long now = clock.getCurrentTime(); - if (now - lastUpdate.longValue() < coolDown) { - return; - } - connPerRoute.setMaxPerRoute(route, getBackedOffPoolSize(curr)); - lastRouteBackoffs.put(route, Long.valueOf(now)); - } - } - - private int getBackedOffPoolSize(final int curr) { - if (curr <= 1) { - return 1; - } - return (int)(Math.floor(backoffFactor * curr)); - } - - public void probe(final HttpRoute route) { - synchronized(connPerRoute) { - final int curr = connPerRoute.getMaxPerRoute(route); - final int max = (curr >= cap) ? cap : curr + 1; - final Long lastProbe = getLastUpdate(lastRouteProbes, route); - final Long lastBackoff = getLastUpdate(lastRouteBackoffs, route); - final long now = clock.getCurrentTime(); - if (now - lastProbe.longValue() < coolDown || now - lastBackoff.longValue() < coolDown) { - return; - } - connPerRoute.setMaxPerRoute(route, max); - lastRouteProbes.put(route, Long.valueOf(now)); - } - } - - private Long getLastUpdate(final Map updates, final HttpRoute route) { - Long lastUpdate = updates.get(route); - if (lastUpdate == null) { - lastUpdate = Long.valueOf(0L); - } - return lastUpdate; - } - - /** - * Sets the factor to use when backing off; the new - * per-host limit will be roughly the current max times - * this factor. Math.floor is applied in the - * case of non-integer outcomes to ensure we actually - * decrease the pool size. Pool sizes are never decreased - * below 1, however. Defaults to 0.5. - * @param d must be between 0.0 and 1.0, exclusive. - */ - public void setBackoffFactor(final double d) { - Args.check(d > 0.0 && d < 1.0, "Backoff factor must be 0.0 < f < 1.0"); - backoffFactor = d; - } - - /** - * Sets the amount of time, in milliseconds, to wait between - * adjustments in pool sizes for a given host, to allow - * enough time for the adjustments to take effect. Defaults - * to 5000L (5 seconds). - * @param l must be positive - */ - public void setCooldownMillis(final long l) { - Args.positive(coolDown, "Cool down"); - coolDown = l; - } - - /** - * Sets the absolute maximum per-host connection pool size to - * probe up to; defaults to 2 (the default per-host max). - * @param cap must be >= 1 - */ - public void setPerHostConnectionCap(final int cap) { - Args.positive(cap, "Per host connection cap"); - this.cap = cap; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/AuthenticationStrategyImpl.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/AuthenticationStrategyImpl.java deleted file mode 100644 index 0640a03a..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/AuthenticationStrategyImpl.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Queue; - -import android.util.Log; - -import org.apache.http.FormattedHeader; -import org.apache.http.Header; -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.Immutable; -import org.apache.http.auth.AuthOption; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AuthSchemeProvider; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.Credentials; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.client.AuthCache; -import org.apache.http.client.AuthenticationStrategy; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.config.AuthSchemes; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.config.Lookup; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -@Immutable -abstract class AuthenticationStrategyImpl implements AuthenticationStrategy { - - private final static String TAG = "HttpClient"; - - private static final List DEFAULT_SCHEME_PRIORITY = - Collections.unmodifiableList(Arrays.asList(AuthSchemes.SPNEGO, - AuthSchemes.KERBEROS, - AuthSchemes.NTLM, - AuthSchemes.DIGEST, - AuthSchemes.BASIC)); - - private final int challengeCode; - private final String headerName; - - AuthenticationStrategyImpl(final int challengeCode, final String headerName) { - super(); - this.challengeCode = challengeCode; - this.headerName = headerName; - } - - public boolean isAuthenticationRequested( - final HttpHost authhost, - final HttpResponse response, - final HttpContext context) { - Args.notNull(response, "HTTP response"); - final int status = response.getStatusLine().getStatusCode(); - return status == this.challengeCode; - } - - public Map getChallenges( - final HttpHost authhost, - final HttpResponse response, - final HttpContext context) throws MalformedChallengeException { - Args.notNull(response, "HTTP response"); - final Header[] headers = response.getHeaders(this.headerName); - final Map map = new HashMap(headers.length); - for (final Header header : headers) { - final CharArrayBuffer buffer; - int pos; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - pos = ((FormattedHeader) header).getValuePos(); - } else { - final String s = header.getValue(); - if (s == null) { - throw new MalformedChallengeException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - pos = 0; - } - while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - final int beginIndex = pos; - while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - final int endIndex = pos; - final String s = buffer.substring(beginIndex, endIndex); - map.put(s.toLowerCase(Locale.ENGLISH), header); - } - return map; - } - - abstract Collection getPreferredAuthSchemes(RequestConfig config); - - public Queue select( - final Map challenges, - final HttpHost authhost, - final HttpResponse response, - final HttpContext context) throws MalformedChallengeException { - Args.notNull(challenges, "Map of auth challenges"); - Args.notNull(authhost, "Host"); - Args.notNull(response, "HTTP response"); - Args.notNull(context, "HTTP context"); - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - final Queue options = new LinkedList(); - final Lookup registry = clientContext.getAuthSchemeRegistry(); - if (registry == null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Auth scheme registry not set in the context"); - } - return options; - } - final CredentialsProvider credsProvider = clientContext.getCredentialsProvider(); - if (credsProvider == null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Credentials provider not set in the context"); - } - return options; - } - final RequestConfig config = clientContext.getRequestConfig(); - Collection authPrefs = getPreferredAuthSchemes(config); - if (authPrefs == null) { - authPrefs = DEFAULT_SCHEME_PRIORITY; - } - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Authentication schemes in the order of preference: " + authPrefs); - } - - for (final String id: authPrefs) { - final Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH)); - if (challenge != null) { - final AuthSchemeProvider authSchemeProvider = registry.lookup(id); - if (authSchemeProvider == null) { - if (Log.isLoggable(TAG, Log.WARN)) { - Log.w(TAG, "Authentication scheme " + id + " not supported"); - // Try again - } - continue; - } - final AuthScheme authScheme = authSchemeProvider.create(context); - authScheme.processChallenge(challenge); - - final AuthScope authScope = new AuthScope( - authhost.getHostName(), - authhost.getPort(), - authScheme.getRealm(), - authScheme.getSchemeName()); - - final Credentials credentials = credsProvider.getCredentials(authScope); - if (credentials != null) { - options.add(new AuthOption(authScheme, credentials)); - } - } else { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Challenge for " + id + " authentication scheme not available"); - // Try again - } - } - } - return options; - } - - public void authSucceeded( - final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) { - Args.notNull(authhost, "Host"); - Args.notNull(authScheme, "Auth scheme"); - Args.notNull(context, "HTTP context"); - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - if (isCachable(authScheme)) { - AuthCache authCache = clientContext.getAuthCache(); - if (authCache == null) { - authCache = new BasicAuthCache(); - clientContext.setAuthCache(authCache); - } - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Caching '" + authScheme.getSchemeName() + - "' auth scheme for " + authhost); - } - authCache.put(authhost, authScheme); - } - } - - protected boolean isCachable(final AuthScheme authScheme) { - if (authScheme == null || !authScheme.isComplete()) { - return false; - } - final String schemeName = authScheme.getSchemeName(); - return schemeName.equalsIgnoreCase(AuthSchemes.BASIC) || - schemeName.equalsIgnoreCase(AuthSchemes.DIGEST); - } - - public void authFailed( - final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) { - Args.notNull(authhost, "Host"); - Args.notNull(context, "HTTP context"); - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - final AuthCache authCache = clientContext.getAuthCache(); - if (authCache != null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Clearing cached auth scheme for " + authhost); - } - authCache.remove(authhost); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/BasicAuthCache.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/BasicAuthCache.java deleted file mode 100644 index bf3a2cfa..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/BasicAuthCache.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.client; - -import java.util.HashMap; - -import org.apache.http.HttpHost; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.auth.AuthScheme; -import org.apache.http.client.AuthCache; -import org.apache.http.conn.SchemePortResolver; -import org.apache.http.conn.UnsupportedSchemeException; -import org.apache.http.impl.conn.DefaultSchemePortResolver; -import org.apache.http.util.Args; - -/** - * Default implementation of {@link AuthCache}. - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicAuthCache implements AuthCache { - - private final HashMap map; - private final SchemePortResolver schemePortResolver; - - /** - * Default constructor. - * - * @since 4.3 - */ - public BasicAuthCache(final SchemePortResolver schemePortResolver) { - super(); - this.map = new HashMap(); - this.schemePortResolver = schemePortResolver != null ? schemePortResolver : - DefaultSchemePortResolver.INSTANCE; - } - - public BasicAuthCache() { - this(null); - } - - protected HttpHost getKey(final HttpHost host) { - if (host.getPort() <= 0) { - final int port; - try { - port = schemePortResolver.resolve(host); - } catch (final UnsupportedSchemeException ignore) { - return host; - } - return new HttpHost(host.getHostName(), port, host.getSchemeName()); - } else { - return host; - } - } - - public void put(final HttpHost host, final AuthScheme authScheme) { - Args.notNull(host, "HTTP host"); - this.map.put(getKey(host), authScheme); - } - - public AuthScheme get(final HttpHost host) { - Args.notNull(host, "HTTP host"); - return this.map.get(getKey(host)); - } - - public void remove(final HttpHost host) { - Args.notNull(host, "HTTP host"); - this.map.remove(getKey(host)); - } - - public void clear() { - this.map.clear(); - } - - @Override - public String toString() { - return this.map.toString(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/BasicCookieStoreHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/BasicCookieStoreHC4.java deleted file mode 100644 index 9533a272..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/BasicCookieStoreHC4.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.client; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.TreeSet; - -import org.apache.http.annotation.GuardedBy; -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.client.CookieStore; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieIdentityComparator; - -/** - * Default implementation of {@link CookieStore} - * - * - * @since 4.0 - */ -@ThreadSafe -public class BasicCookieStoreHC4 implements CookieStore, Serializable { - - private static final long serialVersionUID = -7581093305228232025L; - - @GuardedBy("this") - private final TreeSet cookies; - - public BasicCookieStoreHC4() { - super(); - this.cookies = new TreeSet(new CookieIdentityComparator()); - } - - /** - * Adds an {@link Cookie HTTP cookie}, replacing any existing equivalent cookies. - * If the given cookie has already expired it will not be added, but existing - * values will still be removed. - * - * @param cookie the {@link Cookie cookie} to be added - * - * @see #addCookies(Cookie[]) - * - */ - public synchronized void addCookie(final Cookie cookie) { - if (cookie != null) { - // first remove any old cookie that is equivalent - cookies.remove(cookie); - if (!cookie.isExpired(new Date())) { - cookies.add(cookie); - } - } - } - - /** - * Adds an array of {@link Cookie HTTP cookies}. Cookies are added individually and - * in the given array order. If any of the given cookies has already expired it will - * not be added, but existing values will still be removed. - * - * @param cookies the {@link Cookie cookies} to be added - * - * @see #addCookie(Cookie) - * - */ - public synchronized void addCookies(final Cookie[] cookies) { - if (cookies != null) { - for (final Cookie cooky : cookies) { - this.addCookie(cooky); - } - } - } - - /** - * Returns an immutable array of {@link Cookie cookies} that this HTTP - * state currently contains. - * - * @return an array of {@link Cookie cookies}. - */ - public synchronized List getCookies() { - //create defensive copy so it won't be concurrently modified - return new ArrayList(cookies); - } - - /** - * Removes all of {@link Cookie cookies} in this HTTP state - * that have expired by the specified {@link java.util.Date date}. - * - * @return true if any cookies were purged. - * - * @see Cookie#isExpired(Date) - */ - public synchronized boolean clearExpired(final Date date) { - if (date == null) { - return false; - } - boolean removed = false; - for (final Iterator it = cookies.iterator(); it.hasNext();) { - if (it.next().isExpired(date)) { - it.remove(); - removed = true; - } - } - return removed; - } - - /** - * Clears all cookies. - */ - public synchronized void clear() { - cookies.clear(); - } - - @Override - public synchronized String toString() { - return cookies.toString(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/BasicCredentialsProviderHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/BasicCredentialsProviderHC4.java deleted file mode 100644 index e65cb32e..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/BasicCredentialsProviderHC4.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.client; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.Credentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.util.Args; - -/** - * Default implementation of {@link CredentialsProvider}. - * - * @since 4.0 - */ -@ThreadSafe -public class BasicCredentialsProviderHC4 implements CredentialsProvider { - - private final ConcurrentHashMap credMap; - - /** - * Default constructor. - */ - public BasicCredentialsProviderHC4() { - super(); - this.credMap = new ConcurrentHashMap(); - } - - public void setCredentials( - final AuthScope authscope, - final Credentials credentials) { - Args.notNull(authscope, "Authentication scope"); - credMap.put(authscope, credentials); - } - - /** - * Find matching {@link Credentials credentials} for the given authentication scope. - * - * @param map the credentials hash map - * @param authscope the {@link AuthScope authentication scope} - * @return the credentials - * - */ - private static Credentials matchCredentials( - final Map map, - final AuthScope authscope) { - // see if we get a direct hit - Credentials creds = map.get(authscope); - if (creds == null) { - // Nope. - // Do a full scan - int bestMatchFactor = -1; - AuthScope bestMatch = null; - for (final AuthScope current: map.keySet()) { - final int factor = authscope.match(current); - if (factor > bestMatchFactor) { - bestMatchFactor = factor; - bestMatch = current; - } - } - if (bestMatch != null) { - creds = map.get(bestMatch); - } - } - return creds; - } - - public Credentials getCredentials(final AuthScope authscope) { - Args.notNull(authscope, "Authentication scope"); - return matchCredentials(this.credMap, authscope); - } - - public void clear() { - this.credMap.clear(); - } - - @Override - public String toString() { - return credMap.toString(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/BasicResponseHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/BasicResponseHandlerHC4.java deleted file mode 100644 index 69dc9815..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/BasicResponseHandlerHC4.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.io.IOException; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.StatusLine; -import org.apache.http.annotation.Immutable; -import org.apache.http.client.HttpResponseException; -import org.apache.http.client.ResponseHandler; -import org.apache.http.util.EntityUtilsHC4; - -/** - * A {@link ResponseHandler} that returns the response body as a String - * for successful (2xx) responses. If the response code was >= 300, the response - * body is consumed and an {@link HttpResponseException} is thrown. - *

    - * If this is used with - * {@link org.apache.http.client.HttpClient#execute( - * org.apache.http.client.methods.HttpUriRequest, ResponseHandler)}, - * HttpClient may handle redirects (3xx responses) internally. - * - * @since 4.0 - */ -@Immutable -public class BasicResponseHandlerHC4 implements ResponseHandler { - - /** - * Returns the response body as a String if the response was successful (a - * 2xx status code). If no response body exists, this returns null. If the - * response was unsuccessful (>= 300 status code), throws an - * {@link HttpResponseException}. - */ - public String handleResponse(final HttpResponse response) - throws HttpResponseException, IOException { - final StatusLine statusLine = response.getStatusLine(); - final HttpEntity entity = response.getEntity(); - if (statusLine.getStatusCode() >= 300) { - EntityUtilsHC4.consume(entity); - throw new HttpResponseException(statusLine.getStatusCode(), - statusLine.getReasonPhrase()); - } - return entity == null ? null : EntityUtilsHC4.toString(entity); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/Clock.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/Clock.java deleted file mode 100644 index 012a0bec..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/Clock.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.client; - -/** - * Interface used to enable easier testing of time-related behavior. - * - * @since 4.2 - * - */ -interface Clock { - - /** - * Returns the current time, expressed as the number of - * milliseconds since the epoch. - * @return current time - */ - long getCurrentTime(); -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/CloseableHttpClient.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/CloseableHttpClient.java deleted file mode 100644 index 1e06885e..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/CloseableHttpClient.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.io.Closeable; -import java.io.IOException; -import java.lang.reflect.UndeclaredThrowableException; -import java.net.URI; - -import android.util.Log; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.HttpClient; -import org.apache.http.client.ResponseHandler; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.utils.URIUtilsHC4; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; -import org.apache.http.util.EntityUtilsHC4; - -/** - * Base implementation of {@link HttpClient} that also implements {@link Closeable}. - * - * @since 4.3 - */ -@ThreadSafe -public abstract class CloseableHttpClient implements HttpClient, Closeable { - - private final static String TAG = "HttpClient"; - - protected abstract CloseableHttpResponse doExecute(HttpHost target, HttpRequest request, - HttpContext context) throws IOException, ClientProtocolException; - - /** - * {@inheritDoc} - */ - public CloseableHttpResponse execute( - final HttpHost target, - final HttpRequest request, - final HttpContext context) throws IOException, ClientProtocolException { - return doExecute(target, request, context); - } - - /** - * {@inheritDoc} - */ - public CloseableHttpResponse execute( - final HttpUriRequest request, - final HttpContext context) throws IOException, ClientProtocolException { - Args.notNull(request, "HTTP request"); - return doExecute(determineTarget(request), request, context); - } - - private static HttpHost determineTarget(final HttpUriRequest request) throws ClientProtocolException { - // A null target may be acceptable if there is a default target. - // Otherwise, the null target is detected in the director. - HttpHost target = null; - - final URI requestURI = request.getURI(); - if (requestURI.isAbsolute()) { - target = URIUtilsHC4.extractHost(requestURI); - if (target == null) { - throw new ClientProtocolException("URI does not specify a valid host name: " - + requestURI); - } - } - return target; - } - - /** - * {@inheritDoc} - */ - public CloseableHttpResponse execute( - final HttpUriRequest request) throws IOException, ClientProtocolException { - return execute(request, (HttpContext) null); - } - - /** - * {@inheritDoc} - */ - public CloseableHttpResponse execute( - final HttpHost target, - final HttpRequest request) throws IOException, ClientProtocolException { - return doExecute(target, request, (HttpContext) null); - } - - /** - * Executes a request using the default context and processes the - * response using the given response handler. The content entity associated - * with the response is fully consumed and the underlying connection is - * released back to the connection manager automatically in all cases - * relieving individual {@link ResponseHandler}s from having to manage - * resource deallocation internally. - * - * @param request the request to execute - * @param responseHandler the response handler - * - * @return the response object as generated by the response handler. - * @throws IOException in case of a problem or the connection was aborted - * @throws ClientProtocolException in case of an http protocol error - */ - public T execute(final HttpUriRequest request, - final ResponseHandler responseHandler) throws IOException, - ClientProtocolException { - return execute(request, responseHandler, null); - } - - /** - * Executes a request using the default context and processes the - * response using the given response handler. The content entity associated - * with the response is fully consumed and the underlying connection is - * released back to the connection manager automatically in all cases - * relieving individual {@link ResponseHandler}s from having to manage - * resource deallocation internally. - * - * @param request the request to execute - * @param responseHandler the response handler - * @param context the context to use for the execution, or - * null to use the default context - * - * @return the response object as generated by the response handler. - * @throws IOException in case of a problem or the connection was aborted - * @throws ClientProtocolException in case of an http protocol error - */ - public T execute(final HttpUriRequest request, - final ResponseHandler responseHandler, final HttpContext context) - throws IOException, ClientProtocolException { - final HttpHost target = determineTarget(request); - return execute(target, request, responseHandler, context); - } - - /** - * Executes a request using the default context and processes the - * response using the given response handler. The content entity associated - * with the response is fully consumed and the underlying connection is - * released back to the connection manager automatically in all cases - * relieving individual {@link ResponseHandler}s from having to manage - * resource deallocation internally. - * - * @param target the target host for the request. - * Implementations may accept null - * if they can still determine a route, for example - * to a default target or by inspecting the request. - * @param request the request to execute - * @param responseHandler the response handler - * - * @return the response object as generated by the response handler. - * @throws IOException in case of a problem or the connection was aborted - * @throws ClientProtocolException in case of an http protocol error - */ - public T execute(final HttpHost target, final HttpRequest request, - final ResponseHandler responseHandler) throws IOException, - ClientProtocolException { - return execute(target, request, responseHandler, null); - } - - /** - * Executes a request using the default context and processes the - * response using the given response handler. The content entity associated - * with the response is fully consumed and the underlying connection is - * released back to the connection manager automatically in all cases - * relieving individual {@link ResponseHandler}s from having to manage - * resource deallocation internally. - * - * @param target the target host for the request. - * Implementations may accept null - * if they can still determine a route, for example - * to a default target or by inspecting the request. - * @param request the request to execute - * @param responseHandler the response handler - * @param context the context to use for the execution, or - * null to use the default context - * - * @return the response object as generated by the response handler. - * @throws IOException in case of a problem or the connection was aborted - * @throws ClientProtocolException in case of an http protocol error - */ - public T execute(final HttpHost target, final HttpRequest request, - final ResponseHandler responseHandler, final HttpContext context) - throws IOException, ClientProtocolException { - Args.notNull(responseHandler, "Response handler"); - - final HttpResponse response = execute(target, request, context); - - final T result; - try { - result = responseHandler.handleResponse(response); - } catch (final Exception t) { - final HttpEntity entity = response.getEntity(); - try { - EntityUtilsHC4.consume(entity); - } catch (final Exception t2) { - // Log this exception. The original exception is more - // important and will be thrown to the caller. - if (Log.isLoggable(TAG, Log.WARN)) { - Log.w(TAG, "Error consuming content after an exception.", t2); - } - } - if (t instanceof RuntimeException) { - throw (RuntimeException) t; - } - if (t instanceof IOException) { - throw (IOException) t; - } - throw new UndeclaredThrowableException(t); - } - - // Handling the response was successful. Ensure that the content has - // been fully consumed. - final HttpEntity entity = response.getEntity(); - EntityUtilsHC4.consume(entity); - return result; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/CloseableHttpResponseProxy.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/CloseableHttpResponseProxy.java deleted file mode 100644 index 25e78263..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/CloseableHttpResponseProxy.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.io.IOException; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.util.EntityUtilsHC4; - -/** - * @since 4.3 - */ -@NotThreadSafe -class CloseableHttpResponseProxy implements InvocationHandler { - - private final HttpResponse original; - - CloseableHttpResponseProxy(final HttpResponse original) { - super(); - this.original = original; - } - - public void close() throws IOException { - final HttpEntity entity = this.original.getEntity(); - EntityUtilsHC4.consume(entity); - } - - public Object invoke( - final Object proxy, final Method method, final Object[] args) throws Throwable { - final String mname = method.getName(); - if (mname.equals("close")) { - close(); - return null; - } else { - try { - return method.invoke(original, args); - } catch (final InvocationTargetException ex) { - final Throwable cause = ex.getCause(); - if (cause != null) { - throw cause; - } else { - throw ex; - } - } - } - } - - public static CloseableHttpResponse newProxy(final HttpResponse original) { - return (CloseableHttpResponse) Proxy.newProxyInstance( - CloseableHttpResponseProxy.class.getClassLoader(), - new Class[] { CloseableHttpResponse.class }, - new CloseableHttpResponseProxy(original)); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultBackoffStrategy.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultBackoffStrategy.java deleted file mode 100644 index 3d79034b..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultBackoffStrategy.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.client; - -import java.net.ConnectException; -import java.net.SocketTimeoutException; - -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.client.ConnectionBackoffStrategy; - -/** - * This {@link ConnectionBackoffStrategy} backs off either for a raw - * network socket or connection timeout or if the server explicitly - * sends a 503 (Service Unavailable) response. - * - * @since 4.2 - */ -public class DefaultBackoffStrategy implements ConnectionBackoffStrategy { - - public boolean shouldBackoff(final Throwable t) { - return (t instanceof SocketTimeoutException - || t instanceof ConnectException); - } - - public boolean shouldBackoff(final HttpResponse resp) { - return (resp.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultConnectionKeepAliveStrategyHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultConnectionKeepAliveStrategyHC4.java deleted file mode 100644 index b9f47560..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultConnectionKeepAliveStrategyHC4.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.client; - -import org.apache.http.HeaderElement; -import org.apache.http.HeaderElementIterator; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.Immutable; -import org.apache.http.conn.ConnectionKeepAliveStrategy; -import org.apache.http.message.BasicHeaderElementIterator; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; - -/** - * Default implementation of a strategy deciding duration - * that a connection can remain idle. - * - * The default implementation looks solely at the 'Keep-Alive' - * header's timeout token. - * - * @since 4.0 - */ -@Immutable -public class DefaultConnectionKeepAliveStrategyHC4 implements ConnectionKeepAliveStrategy { - - public static final DefaultConnectionKeepAliveStrategyHC4 INSTANCE = new DefaultConnectionKeepAliveStrategyHC4(); - - public long getKeepAliveDuration(final HttpResponse response, final HttpContext context) { - Args.notNull(response, "HTTP response"); - final HeaderElementIterator it = new BasicHeaderElementIterator( - response.headerIterator(HTTP.CONN_KEEP_ALIVE)); - while (it.hasNext()) { - final HeaderElement he = it.nextElement(); - final String param = he.getName(); - final String value = he.getValue(); - if (value != null && param.equalsIgnoreCase("timeout")) { - try { - return Long.parseLong(value) * 1000; - } catch(final NumberFormatException ignore) { - } - } - } - return -1; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultHttpRequestRetryHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultHttpRequestRetryHandlerHC4.java deleted file mode 100644 index 14ffe296..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultHttpRequestRetryHandlerHC4.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.ConnectException; -import java.net.UnknownHostException; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -import javax.net.ssl.SSLException; - -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpRequest; -import org.apache.http.annotation.Immutable; -import org.apache.http.client.HttpRequestRetryHandler; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; - -/** - * The default {@link HttpRequestRetryHandler} used by request executors. - * - * @since 4.0 - */ -@Immutable -public class DefaultHttpRequestRetryHandlerHC4 implements HttpRequestRetryHandler { - - public static final DefaultHttpRequestRetryHandlerHC4 INSTANCE = new DefaultHttpRequestRetryHandlerHC4(); - - /** the number of times a method will be retried */ - private final int retryCount; - - /** Whether or not methods that have successfully sent their request will be retried */ - private final boolean requestSentRetryEnabled; - - private final Set> nonRetriableClasses; - - /** - * Create the request retry handler using the specified IOException classes - * - * @param retryCount how many times to retry; 0 means no retries - * @param requestSentRetryEnabled true if it's OK to retry requests that have been sent - * @param clazzes the IOException types that should not be retried - * @since 4.3 - */ - protected DefaultHttpRequestRetryHandlerHC4( - final int retryCount, - final boolean requestSentRetryEnabled, - final Collection> clazzes) { - super(); - this.retryCount = retryCount; - this.requestSentRetryEnabled = requestSentRetryEnabled; - this.nonRetriableClasses = new HashSet>(); - for (final Class clazz: clazzes) { - this.nonRetriableClasses.add(clazz); - } - } - - /** - * Create the request retry handler using the following list of - * non-retriable IOException classes:
    - *

      - *
    • InterruptedIOException
    • - *
    • UnknownHostException
    • - *
    • ConnectException
    • - *
    • SSLException
    • - *
    - * @param retryCount how many times to retry; 0 means no retries - * @param requestSentRetryEnabled true if it's OK to retry requests that have been sent - */ - @SuppressWarnings("unchecked") - public DefaultHttpRequestRetryHandlerHC4(final int retryCount, final boolean requestSentRetryEnabled) { - this(retryCount, requestSentRetryEnabled, Arrays.asList( - InterruptedIOException.class, - UnknownHostException.class, - ConnectException.class, - SSLException.class)); - } - - /** - * Create the request retry handler with a retry count of 3, requestSentRetryEnabled false - * and using the following list of non-retriable IOException classes:
    - *
      - *
    • InterruptedIOException
    • - *
    • UnknownHostException
    • - *
    • ConnectException
    • - *
    • SSLException
    • - *
    - */ - public DefaultHttpRequestRetryHandlerHC4() { - this(3, false); - } - /** - * Used retryCount and requestSentRetryEnabled to determine - * if the given method should be retried. - */ - public boolean retryRequest( - final IOException exception, - final int executionCount, - final HttpContext context) { - Args.notNull(exception, "Exception parameter"); - Args.notNull(context, "HTTP context"); - if (executionCount > this.retryCount) { - // Do not retry if over max retry count - return false; - } - if (this.nonRetriableClasses.contains(exception.getClass())) { - return false; - } else { - for (final Class rejectException : this.nonRetriableClasses) { - if (rejectException.isInstance(exception)) { - return false; - } - } - } - final HttpClientContext clientContext = HttpClientContext.adapt(context); - final HttpRequest request = clientContext.getRequest(); - - if(requestIsAborted(request)){ - return false; - } - - if (handleAsIdempotent(request)) { - // Retry if the request is considered idempotent - return true; - } - - if (!clientContext.isRequestSent() || this.requestSentRetryEnabled) { - // Retry if the request has not been sent fully or - // if it's OK to retry methods that have been sent - return true; - } - // otherwise do not retry - return false; - } - - /** - * @return true if this handler will retry methods that have - * successfully sent their request, false otherwise - */ - public boolean isRequestSentRetryEnabled() { - return requestSentRetryEnabled; - } - - /** - * @return the maximum number of times a method will be retried - */ - public int getRetryCount() { - return retryCount; - } - - /** - * @since 4.2 - */ - protected boolean handleAsIdempotent(final HttpRequest request) { - return !(request instanceof HttpEntityEnclosingRequest); - } - - /** - * @since 4.2 - * - * @deprecated (4.3) - */ - @Deprecated - protected boolean requestIsAborted(final HttpRequest request) { - HttpRequest req = request; - if (request instanceof RequestWrapper) { // does not forward request to original - req = ((RequestWrapper) request).getOriginal(); - } - return (req instanceof HttpUriRequest && ((HttpUriRequest)req).isAborted()); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultRedirectStrategy.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultRedirectStrategy.java deleted file mode 100644 index 4cd2fb70..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultRedirectStrategy.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Locale; - -import android.util.Log; - -import org.apache.http.Header; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.ProtocolException; -import org.apache.http.annotation.Immutable; -import org.apache.http.client.CircularRedirectException; -import org.apache.http.client.RedirectStrategy; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpGetHC4; -import org.apache.http.client.methods.HttpHeadHC4; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.methods.RequestBuilder; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.client.utils.URIUtilsHC4; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; -import org.apache.http.util.Asserts; -import org.apache.http.util.TextUtils; - -/** - * Default implementation of {@link RedirectStrategy}. This strategy honors the restrictions - * on automatic redirection of entity enclosing methods such as POST and PUT imposed by the - * HTTP specification. 302 Moved Temporarily, 301 Moved Permanently and - * 307 Temporary Redirect status codes will result in an automatic redirect of - * HEAD and GET methods only. POST and PUT methods will not be automatically redirected - * as requiring user confirmation. - *

    - * The restriction on automatic redirection of POST methods can be relaxed by using - * {@link LaxRedirectStrategy} instead of {@link DefaultRedirectStrategy}. - * - * @see LaxRedirectStrategy - * @since 4.1 - */ -@Immutable -public class DefaultRedirectStrategy implements RedirectStrategy { - - private final static String TAG = "HttpClient"; - - /** - * @deprecated (4.3) use {@link org.apache.http.client.protocol.HttpClientContext#REDIRECT_LOCATIONS}. - */ - @Deprecated - public static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations"; - - public static final DefaultRedirectStrategy INSTANCE = new DefaultRedirectStrategy(); - - /** - * Redirectable methods. - */ - private static final String[] REDIRECT_METHODS = new String[] { - HttpGetHC4.METHOD_NAME, - HttpHeadHC4.METHOD_NAME - }; - - public DefaultRedirectStrategy() { - super(); - } - - public boolean isRedirected( - final HttpRequest request, - final HttpResponse response, - final HttpContext context) throws ProtocolException { - Args.notNull(request, "HTTP request"); - Args.notNull(response, "HTTP response"); - - final int statusCode = response.getStatusLine().getStatusCode(); - final String method = request.getRequestLine().getMethod(); - final Header locationHeader = response.getFirstHeader("location"); - switch (statusCode) { - case HttpStatus.SC_MOVED_TEMPORARILY: - return isRedirectable(method) && locationHeader != null; - case HttpStatus.SC_MOVED_PERMANENTLY: - case HttpStatus.SC_TEMPORARY_REDIRECT: - return isRedirectable(method); - case HttpStatus.SC_SEE_OTHER: - return true; - default: - return false; - } //end of switch - } - - public URI getLocationURI( - final HttpRequest request, - final HttpResponse response, - final HttpContext context) throws ProtocolException { - Args.notNull(request, "HTTP request"); - Args.notNull(response, "HTTP response"); - Args.notNull(context, "HTTP context"); - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - //get the location header to find out where to redirect to - final Header locationHeader = response.getFirstHeader("location"); - if (locationHeader == null) { - // got a redirect response, but no location header - throw new ProtocolException( - "Received redirect response " + response.getStatusLine() - + " but no location header"); - } - final String location = locationHeader.getValue(); - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Redirect requested to location '" + location + "'"); - } - - final RequestConfig config = clientContext.getRequestConfig(); - - URI uri = createLocationURI(location); - - // rfc2616 demands the location value be a complete URI - // Location = "Location" ":" absoluteURI - try { - if (!uri.isAbsolute()) { - if (!config.isRelativeRedirectsAllowed()) { - throw new ProtocolException("Relative redirect location '" - + uri + "' not allowed"); - } - // Adjust location URI - final HttpHost target = clientContext.getTargetHost(); - Asserts.notNull(target, "Target host"); - final URI requestURI = new URI(request.getRequestLine().getUri()); - final URI absoluteRequestURI = URIUtilsHC4.rewriteURI(requestURI, target, false); - uri = URIUtilsHC4.resolve(absoluteRequestURI, uri); - } - } catch (final URISyntaxException ex) { - throw new ProtocolException(ex.getMessage(), ex); - } - - RedirectLocationsHC4 redirectLocations = (RedirectLocationsHC4) clientContext.getAttribute( - HttpClientContext.REDIRECT_LOCATIONS); - if (redirectLocations == null) { - redirectLocations = new RedirectLocationsHC4(); - context.setAttribute(HttpClientContext.REDIRECT_LOCATIONS, redirectLocations); - } - if (!config.isCircularRedirectsAllowed()) { - if (redirectLocations.contains(uri)) { - throw new CircularRedirectException("Circular redirect to '" + uri + "'"); - } - } - redirectLocations.add(uri); - return uri; - } - - /** - * @since 4.1 - */ - protected URI createLocationURI(final String location) throws ProtocolException { - try { - final URIBuilder b = new URIBuilder(new URI(location).normalize()); - final String host = b.getHost(); - if (host != null) { - b.setHost(host.toLowerCase(Locale.ENGLISH)); - } - final String path = b.getPath(); - if (TextUtils.isEmpty(path)) { - b.setPath("/"); - } - return b.build(); - } catch (final URISyntaxException ex) { - throw new ProtocolException("Invalid redirect URI: " + location, ex); - } - } - - /** - * @since 4.2 - */ - protected boolean isRedirectable(final String method) { - for (final String m: REDIRECT_METHODS) { - if (m.equalsIgnoreCase(method)) { - return true; - } - } - return false; - } - - public HttpUriRequest getRedirect( - final HttpRequest request, - final HttpResponse response, - final HttpContext context) throws ProtocolException { - final URI uri = getLocationURI(request, response, context); - final String method = request.getRequestLine().getMethod(); - if (method.equalsIgnoreCase(HttpHeadHC4.METHOD_NAME)) { - return new HttpHeadHC4(uri); - } else if (method.equalsIgnoreCase(HttpGetHC4.METHOD_NAME)) { - return new HttpGetHC4(uri); - } else { - final int status = response.getStatusLine().getStatusCode(); - if (status == HttpStatus.SC_TEMPORARY_REDIRECT) { - return RequestBuilder.copy(request).setUri(uri).build(); - } else { - return new HttpGetHC4(uri); - } - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultServiceUnavailableRetryStrategy.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultServiceUnavailableRetryStrategy.java deleted file mode 100644 index b5d76ea5..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultServiceUnavailableRetryStrategy.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.annotation.Immutable; -import org.apache.http.client.ServiceUnavailableRetryStrategy; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; - -/** - * Default implementation of the {@link ServiceUnavailableRetryStrategy} interface. - * that retries 503 (Service Unavailable) responses for a fixed number of times - * at a fixed interval. - * - * @since 4.2 - */ -@Immutable -public class DefaultServiceUnavailableRetryStrategy implements ServiceUnavailableRetryStrategy { - - /** - * Maximum number of allowed retries if the server responds with a HTTP code - * in our retry code list. Default value is 1. - */ - private final int maxRetries; - - /** - * Retry interval between subsequent requests, in milliseconds. Default - * value is 1 second. - */ - private final long retryInterval; - - public DefaultServiceUnavailableRetryStrategy(final int maxRetries, final int retryInterval) { - super(); - Args.positive(maxRetries, "Max retries"); - Args.positive(retryInterval, "Retry interval"); - this.maxRetries = maxRetries; - this.retryInterval = retryInterval; - } - - public DefaultServiceUnavailableRetryStrategy() { - this(1, 1000); - } - - public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) { - return executionCount <= maxRetries && - response.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE; - } - - public long getRetryInterval() { - return retryInterval; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultUserTokenHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultUserTokenHandlerHC4.java deleted file mode 100644 index 299f2592..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/DefaultUserTokenHandlerHC4.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.client; - -import java.security.Principal; - -import javax.net.ssl.SSLSession; - -import org.apache.http.HttpConnection; -import org.apache.http.annotation.Immutable; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AuthStateHC4; -import org.apache.http.auth.Credentials; -import org.apache.http.client.UserTokenHandler; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.conn.ManagedHttpClientConnection; -import org.apache.http.protocol.HttpContext; - -/** - * Default implementation of {@link UserTokenHandler}. This class will use - * an instance of {@link Principal} as a state object for HTTP connections, - * if it can be obtained from the given execution context. This helps ensure - * persistent connections created with a particular user identity within - * a particular security context can be reused by the same user only. - *

    - * DefaultUserTokenHandlerHC4 will use the user principle of connection - * based authentication schemes such as NTLM or that of the SSL session - * with the client authentication turned on. If both are unavailable, - * null token will be returned. - * - * @since 4.0 - */ -@Immutable -public class DefaultUserTokenHandlerHC4 implements UserTokenHandler { - - public static final DefaultUserTokenHandlerHC4 INSTANCE = new DefaultUserTokenHandlerHC4(); - - public Object getUserToken(final HttpContext context) { - - final HttpClientContext clientContext = HttpClientContext.adapt(context); - - Principal userPrincipal = null; - - final AuthStateHC4 targetAuthState = clientContext.getTargetAuthState(); - if (targetAuthState != null) { - userPrincipal = getAuthPrincipal(targetAuthState); - if (userPrincipal == null) { - final AuthStateHC4 proxyAuthState = clientContext.getProxyAuthState(); - userPrincipal = getAuthPrincipal(proxyAuthState); - } - } - - if (userPrincipal == null) { - final HttpConnection conn = clientContext.getConnection(); - if (conn.isOpen() && conn instanceof ManagedHttpClientConnection) { - final SSLSession sslsession = ((ManagedHttpClientConnection) conn).getSSLSession(); - if (sslsession != null) { - userPrincipal = sslsession.getLocalPrincipal(); - } - } - } - - return userPrincipal; - } - - private static Principal getAuthPrincipal(final AuthStateHC4 authState) { - final AuthScheme scheme = authState.getAuthScheme(); - if (scheme != null && scheme.isComplete() && scheme.isConnectionBased()) { - final Credentials creds = authState.getCredentials(); - if (creds != null) { - return creds.getUserPrincipal(); - } - } - return null; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/EntityEnclosingRequestWrapperHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/EntityEnclosingRequestWrapperHC4.java deleted file mode 100644 index a17dcabf..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/EntityEnclosingRequestWrapperHC4.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.ProtocolException; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.entity.HttpEntityWrapperHC4; -import org.apache.http.protocol.HTTP; - -/** - * A wrapper class for {@link HttpEntityEnclosingRequest}s that can - * be used to change properties of the current request without - * modifying the original object. - *

    - * This class is also capable of resetting the request headers to - * the state of the original request. - * - * @since 4.0 - * - * @deprecated (4.3) do not use. - */ -@Deprecated -@NotThreadSafe // e.g. [gs]etEntity() -public class EntityEnclosingRequestWrapperHC4 extends RequestWrapper - implements HttpEntityEnclosingRequest { - - private HttpEntity entity; - private boolean consumed; - - public EntityEnclosingRequestWrapperHC4(final HttpEntityEnclosingRequest request) - throws ProtocolException { - super(request); - setEntity(request.getEntity()); - } - - public HttpEntity getEntity() { - return this.entity; - } - - public void setEntity(final HttpEntity entity) { - this.entity = entity != null ? new EntityWrapper(entity) : null; - this.consumed = false; - } - - public boolean expectContinue() { - final Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE); - return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue()); - } - - @Override - public boolean isRepeatable() { - return this.entity == null || this.entity.isRepeatable() || !this.consumed; - } - - class EntityWrapper extends HttpEntityWrapperHC4 { - - EntityWrapper(final HttpEntity entity) { - super(entity); - } - - @Override - public void consumeContent() throws IOException { - consumed = true; - super.consumeContent(); - } - - @Override - public InputStream getContent() throws IOException { - consumed = true; - return super.getContent(); - } - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - consumed = true; - super.writeTo(outstream); - } - - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/FutureRequestExecutionMetrics.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/FutureRequestExecutionMetrics.java deleted file mode 100644 index 6428e388..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/FutureRequestExecutionMetrics.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.client; - -import java.util.concurrent.atomic.AtomicLong; - -/** - * Collection of different counters used to gather metrics for {@link FutureRequestExecutionService}. - */ -public final class FutureRequestExecutionMetrics { - - private final AtomicLong activeConnections = new AtomicLong(); - private final AtomicLong scheduledConnections = new AtomicLong(); - private final DurationCounter successfulConnections = new DurationCounter(); - private final DurationCounter failedConnections = new DurationCounter(); - private final DurationCounter requests = new DurationCounter(); - private final DurationCounter tasks = new DurationCounter(); - - FutureRequestExecutionMetrics() { - } - - AtomicLong getActiveConnections() { - return activeConnections; - } - - AtomicLong getScheduledConnections() { - return scheduledConnections; - } - - DurationCounter getSuccessfulConnections() { - return successfulConnections; - } - - DurationCounter getFailedConnections() { - return failedConnections; - } - - DurationCounter getRequests() { - return requests; - } - - DurationCounter getTasks() { - return tasks; - } - - public long getActiveConnectionCount() { - return activeConnections.get(); - } - - public long getScheduledConnectionCount() { - return scheduledConnections.get(); - } - - public long getSuccessfulConnectionCount() { - return successfulConnections.count(); - } - - public long getSuccessfulConnectionAverageDuration() { - return successfulConnections.averageDuration(); - } - - public long getFailedConnectionCount() { - return failedConnections.count(); - } - - public long getFailedConnectionAverageDuration() { - return failedConnections.averageDuration(); - } - - public long getRequestCount() { - return requests.count(); - } - - public long getRequestAverageDuration() { - return requests.averageDuration(); - } - - public long getTaskCount() { - return tasks.count(); - } - - public long getTaskAverageDuration() { - return tasks.averageDuration(); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("[activeConnections=").append(activeConnections) - .append(", scheduledConnections=").append(scheduledConnections) - .append(", successfulConnections=").append(successfulConnections) - .append(", failedConnections=").append(failedConnections) - .append(", requests=").append(requests) - .append(", tasks=").append(tasks) - .append("]"); - return builder.toString(); - } - - /** - * A counter that can measure duration and number of events. - */ - static class DurationCounter { - - private final AtomicLong count = new AtomicLong(0); - private final AtomicLong cumulativeDuration = new AtomicLong(0); - - public void increment(final long startTime) { - count.incrementAndGet(); - cumulativeDuration.addAndGet(System.currentTimeMillis() - startTime); - } - - public long count() { - return count.get(); - } - - public long averageDuration() { - final long counter = count.get(); - return counter > 0 ? cumulativeDuration.get() / counter : 0; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("[count=").append(count()) - .append(", averageDuration=").append(averageDuration()) - .append("]"); - return builder.toString(); - } - - } - -} \ No newline at end of file diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/FutureRequestExecutionService.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/FutureRequestExecutionService.java deleted file mode 100644 index 8e03fa3b..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/FutureRequestExecutionService.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.client; - -import java.io.Closeable; -import java.io.IOException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.client.HttpClient; -import org.apache.http.client.ResponseHandler; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.concurrent.FutureCallback; -import org.apache.http.protocol.HttpContext; - -/** - * HttpAsyncClientWithFuture wraps calls to execute with a {@link HttpRequestFutureTask} - * and schedules them using the provided executor service. Scheduled calls may be cancelled. - */ -@ThreadSafe -public class FutureRequestExecutionService implements Closeable { - - private final HttpClient httpclient; - private final ExecutorService executorService; - private final FutureRequestExecutionMetrics metrics = new FutureRequestExecutionMetrics(); - private final AtomicBoolean closed = new AtomicBoolean(false); - - /** - * Create a new FutureRequestExecutionService. - * - * @param httpclient - * you should tune your httpclient instance to match your needs. You should - * align the max number of connections in the pool and the number of threads - * in the executor; it doesn't make sense to have more threads than connections - * and if you have less connections than threads, the threads will just end up - * blocking on getting a connection from the pool. - * @param executorService - * any executorService will do here. E.g. - * {@link java.util.concurrent.Executors#newFixedThreadPool(int)} - */ - public FutureRequestExecutionService( - final HttpClient httpclient, - final ExecutorService executorService) { - this.httpclient = httpclient; - this.executorService = executorService; - } - - /** - * Schedule a request for execution. - * - * @param - * - * @param request - * request to execute - * @param responseHandler - * handler that will process the response. - * @return HttpAsyncClientFutureTask for the scheduled request. - * @throws InterruptedException - */ - public HttpRequestFutureTask execute( - final HttpUriRequest request, - final HttpContext context, - final ResponseHandler responseHandler) { - return execute(request, context, responseHandler, null); - } - - /** - * Schedule a request for execution. - * - * @param - * - * @param request - * request to execute - * @param context - * optional context; use null if not needed. - * @param responseHandler - * handler that will process the response. - * @param callback - * callback handler that will be called when the request is scheduled, - * started, completed, failed, or cancelled. - * @return HttpAsyncClientFutureTask for the scheduled request. - * @throws InterruptedException - */ - public HttpRequestFutureTask execute( - final HttpUriRequest request, - final HttpContext context, - final ResponseHandler responseHandler, - final FutureCallback callback) { - if(closed.get()) { - throw new IllegalStateException("Close has been called on this httpclient instance."); - } - metrics.getScheduledConnections().incrementAndGet(); - final HttpRequestTaskCallable callable = new HttpRequestTaskCallable( - httpclient, request, context, responseHandler, callback, metrics); - final HttpRequestFutureTask httpRequestFutureTask = new HttpRequestFutureTask( - request, callable); - executorService.execute(httpRequestFutureTask); - - return httpRequestFutureTask; - } - - /** - * @return metrics gathered for this instance. - * @see FutureRequestExecutionMetrics - */ - public FutureRequestExecutionMetrics metrics() { - return metrics; - } - - public void close() throws IOException { - closed.set(true); - executorService.shutdownNow(); - if (httpclient instanceof Closeable) { - ((Closeable) httpclient).close(); - } - } -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/HttpClientBuilder.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/HttpClientBuilder.java deleted file mode 100644 index 94d9df59..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/HttpClientBuilder.java +++ /dev/null @@ -1,951 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import android.net.SSLCertificateSocketFactory; - -import java.io.Closeable; -import java.net.ProxySelector; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocketFactory; - -import org.apache.http.ConnectionReuseStrategy; -import org.apache.http.Header; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.HttpResponseInterceptor; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.auth.AuthSchemeProvider; -import org.apache.http.client.AuthenticationStrategy; -import org.apache.http.client.BackoffManager; -import org.apache.http.client.ConnectionBackoffStrategy; -import org.apache.http.client.CookieStore; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.HttpRequestRetryHandler; -import org.apache.http.client.RedirectStrategy; -import org.apache.http.client.ServiceUnavailableRetryStrategy; -import org.apache.http.client.UserTokenHandler; -import org.apache.http.client.config.AuthSchemes; -import org.apache.http.client.config.CookieSpecs; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.protocol.RequestAcceptEncoding; -import org.apache.http.client.protocol.RequestAddCookiesHC4; -import org.apache.http.client.protocol.RequestAuthCache; -import org.apache.http.client.protocol.RequestClientConnControl; -import org.apache.http.client.protocol.RequestDefaultHeadersHC4; -import org.apache.http.client.protocol.RequestExpectContinue; -import org.apache.http.client.protocol.ResponseContentEncoding; -import org.apache.http.client.protocol.ResponseProcessCookiesHC4; -import org.apache.http.config.ConnectionConfig; -import org.apache.http.config.Lookup; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.config.SocketConfig; -import org.apache.http.conn.ConnectionKeepAliveStrategy; -import org.apache.http.conn.HttpClientConnectionManager; -import org.apache.http.conn.SchemePortResolver; -import org.apache.http.conn.routing.HttpRoutePlanner; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.LayeredConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.X509HostnameVerifier; -import org.apache.http.cookie.CookieSpecProvider; -import org.apache.http.impl.DefaultConnectionReuseStrategyHC4; -import org.apache.http.impl.NoConnectionReuseStrategyHC4; -import org.apache.http.impl.auth.BasicSchemeFactoryHC4; -import org.apache.http.impl.auth.DigestSchemeFactoryHC4; -import org.apache.http.impl.auth.NTLMSchemeFactory; -import org.apache.http.impl.conn.DefaultProxyRoutePlanner; -import org.apache.http.impl.conn.DefaultRoutePlanner; -import org.apache.http.impl.conn.DefaultSchemePortResolver; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.impl.conn.SystemDefaultRoutePlanner; -import org.apache.http.impl.cookie.BestMatchSpecFactoryHC4; -import org.apache.http.impl.cookie.BrowserCompatSpecFactoryHC4; -import org.apache.http.impl.cookie.IgnoreSpecFactory; -import org.apache.http.impl.cookie.NetscapeDraftSpecFactoryHC4; -import org.apache.http.impl.cookie.RFC2109SpecFactoryHC4; -import org.apache.http.impl.cookie.RFC2965SpecFactoryHC4; -import org.apache.http.impl.execchain.BackoffStrategyExec; -import org.apache.http.impl.execchain.ClientExecChain; -import org.apache.http.impl.execchain.MainClientExec; -import org.apache.http.impl.execchain.ProtocolExec; -import org.apache.http.impl.execchain.RedirectExec; -import org.apache.http.impl.execchain.RetryExec; -import org.apache.http.impl.execchain.ServiceUnavailableRetryExec; -import org.apache.http.protocol.HttpProcessor; -import org.apache.http.protocol.HttpProcessorBuilder; -import org.apache.http.protocol.HttpRequestExecutor; -import org.apache.http.protocol.RequestContentHC4; -import org.apache.http.protocol.RequestTargetHostHC4; -import org.apache.http.protocol.RequestUserAgentHC4; -import org.apache.http.util.TextUtils; -import org.apache.http.util.VersionInfoHC4; - -/** - * Builder for {@link CloseableHttpClient} instances. - *

    - * When a particular component is not explicitly this class will - * use its default implementation. System properties will be taken - * into account when configuring the default implementations when - * {@link #useSystemProperties()} method is called prior to calling - * {@link #build()}. - *

      - *
    • ssl.TrustManagerFactory.algorithm
    • - *
    • javax.net.ssl.trustStoreType
    • - *
    • javax.net.ssl.trustStore
    • - *
    • javax.net.ssl.trustStoreProvider
    • - *
    • javax.net.ssl.trustStorePassword
    • - *
    • ssl.KeyManagerFactory.algorithm
    • - *
    • javax.net.ssl.keyStoreType
    • - *
    • javax.net.ssl.keyStore
    • - *
    • javax.net.ssl.keyStoreProvider
    • - *
    • javax.net.ssl.keyStorePassword
    • - *
    • https.protocols
    • - *
    • https.cipherSuites
    • - *
    • http.proxyHost
    • - *
    • http.proxyPort
    • - *
    • http.nonProxyHosts
    • - *
    • http.keepAlive
    • - *
    • http.maxConnections
    • - *
    • http.agent
    • - *
    - *

    - * Please note that some settings used by this class can be mutually - * exclusive and may not apply when building {@link CloseableHttpClient} - * instances. - * - * @since 4.3 - */ -@NotThreadSafe -public class HttpClientBuilder { - - private HttpRequestExecutor requestExec; - private X509HostnameVerifier hostnameVerifier; - private LayeredConnectionSocketFactory sslSocketFactory; - private SSLContext sslcontext; - private HttpClientConnectionManager connManager; - private SchemePortResolver schemePortResolver; - private ConnectionReuseStrategy reuseStrategy; - private ConnectionKeepAliveStrategy keepAliveStrategy; - private AuthenticationStrategy targetAuthStrategy; - private AuthenticationStrategy proxyAuthStrategy; - private UserTokenHandler userTokenHandler; - private HttpProcessor httpprocessor; - - private LinkedList requestFirst; - private LinkedList requestLast; - private LinkedList responseFirst; - private LinkedList responseLast; - - private HttpRequestRetryHandler retryHandler; - private HttpRoutePlanner routePlanner; - private RedirectStrategy redirectStrategy; - private ConnectionBackoffStrategy connectionBackoffStrategy; - private BackoffManager backoffManager; - private ServiceUnavailableRetryStrategy serviceUnavailStrategy; - private Lookup authSchemeRegistry; - private Lookup cookieSpecRegistry; - private CookieStore cookieStore; - private CredentialsProvider credentialsProvider; - private String userAgent; - private HttpHost proxy; - private Collection defaultHeaders; - private SocketConfig defaultSocketConfig; - private ConnectionConfig defaultConnectionConfig; - private RequestConfig defaultRequestConfig; - - private boolean systemProperties; - private boolean redirectHandlingDisabled; - private boolean automaticRetriesDisabled; - private boolean contentCompressionDisabled; - private boolean cookieManagementDisabled; - private boolean authCachingDisabled; - private boolean connectionStateDisabled; - - private int maxConnTotal = 0; - private int maxConnPerRoute = 0; - - private List closeables; - - static final String DEFAULT_USER_AGENT; - static { - final VersionInfoHC4 vi = VersionInfoHC4.loadVersionInfo - ("org.apache.http.client", HttpClientBuilder.class.getClassLoader()); - final String release = (vi != null) ? - vi.getRelease() : VersionInfoHC4.UNAVAILABLE; - DEFAULT_USER_AGENT = "Apache-HttpClient/" + release + " (java 1.5)"; - } - - public static HttpClientBuilder create() { - return new HttpClientBuilder(); - } - - protected HttpClientBuilder() { - super(); - } - - /** - * Assigns {@link HttpRequestExecutor} instance. - */ - public final HttpClientBuilder setRequestExecutor(final HttpRequestExecutor requestExec) { - this.requestExec = requestExec; - return this; - } - - /** - * Assigns {@link X509HostnameVerifier} instance. - *

    - * Please note this value can be overridden by the {@link #setConnectionManager( - * org.apache.http.conn.HttpClientConnectionManager)} and the {@link #setSSLSocketFactory( - * org.apache.http.conn.socket.LayeredConnectionSocketFactory)} methods. - */ - public final HttpClientBuilder setHostnameVerifier(final X509HostnameVerifier hostnameVerifier) { - this.hostnameVerifier = hostnameVerifier; - return this; - } - - /** - * Assigns {@link SSLContext} instance. - *

    - *

    - * Please note this value can be overridden by the {@link #setConnectionManager( - * org.apache.http.conn.HttpClientConnectionManager)} and the {@link #setSSLSocketFactory( - * org.apache.http.conn.socket.LayeredConnectionSocketFactory)} methods. - */ - public final HttpClientBuilder setSslcontext(final SSLContext sslcontext) { - this.sslcontext = sslcontext; - return this; - } - - /** - * Assigns {@link LayeredConnectionSocketFactory} instance. - *

    - * Please note this value can be overridden by the {@link #setConnectionManager( - * org.apache.http.conn.HttpClientConnectionManager)} method. - */ - public final HttpClientBuilder setSSLSocketFactory( - final LayeredConnectionSocketFactory sslSocketFactory) { - this.sslSocketFactory = sslSocketFactory; - return this; - } - - /** - * Assigns maximum total connection value. - *

    - * Please note this value can be overridden by the {@link #setConnectionManager( - * org.apache.http.conn.HttpClientConnectionManager)} method. - */ - public final HttpClientBuilder setMaxConnTotal(final int maxConnTotal) { - this.maxConnTotal = maxConnTotal; - return this; - } - - /** - * Assigns maximum connection per route value. - *

    - * Please note this value can be overridden by the {@link #setConnectionManager( - * org.apache.http.conn.HttpClientConnectionManager)} method. - */ - public final HttpClientBuilder setMaxConnPerRoute(final int maxConnPerRoute) { - this.maxConnPerRoute = maxConnPerRoute; - return this; - } - - /** - * Assigns default {@link SocketConfig}. - *

    - * Please note this value can be overridden by the {@link #setConnectionManager( - * org.apache.http.conn.HttpClientConnectionManager)} method. - */ - public final HttpClientBuilder setDefaultSocketConfig(final SocketConfig config) { - this.defaultSocketConfig = config; - return this; - } - - /** - * Assigns default {@link ConnectionConfig}. - *

    - * Please note this value can be overridden by the {@link #setConnectionManager( - * org.apache.http.conn.HttpClientConnectionManager)} method. - */ - public final HttpClientBuilder setDefaultConnectionConfig(final ConnectionConfig config) { - this.defaultConnectionConfig = config; - return this; - } - - /** - * Assigns {@link HttpClientConnectionManager} instance. - */ - public final HttpClientBuilder setConnectionManager( - final HttpClientConnectionManager connManager) { - this.connManager = connManager; - return this; - } - - /** - * Assigns {@link ConnectionReuseStrategy} instance. - */ - public final HttpClientBuilder setConnectionReuseStrategy( - final ConnectionReuseStrategy reuseStrategy) { - this.reuseStrategy = reuseStrategy; - return this; - } - - /** - * Assigns {@link ConnectionKeepAliveStrategy} instance. - */ - public final HttpClientBuilder setKeepAliveStrategy( - final ConnectionKeepAliveStrategy keepAliveStrategy) { - this.keepAliveStrategy = keepAliveStrategy; - return this; - } - - /** - * Assigns {@link AuthenticationStrategy} instance for proxy - * authentication. - */ - public final HttpClientBuilder setTargetAuthenticationStrategy( - final AuthenticationStrategy targetAuthStrategy) { - this.targetAuthStrategy = targetAuthStrategy; - return this; - } - - /** - * Assigns {@link AuthenticationStrategy} instance for target - * host authentication. - */ - public final HttpClientBuilder setProxyAuthenticationStrategy( - final AuthenticationStrategy proxyAuthStrategy) { - this.proxyAuthStrategy = proxyAuthStrategy; - return this; - } - - /** - * Assigns {@link UserTokenHandler} instance. - *

    - * Please note this value can be overridden by the {@link #disableConnectionState()} - * method. - */ - public final HttpClientBuilder setUserTokenHandler(final UserTokenHandler userTokenHandler) { - this.userTokenHandler = userTokenHandler; - return this; - } - - /** - * Disables connection state tracking. - */ - public final HttpClientBuilder disableConnectionState() { - connectionStateDisabled = true; - return this; - } - - /** - * Assigns {@link SchemePortResolver} instance. - */ - public final HttpClientBuilder setSchemePortResolver( - final SchemePortResolver schemePortResolver) { - this.schemePortResolver = schemePortResolver; - return this; - } - - /** - * Assigns User-Agent value. - *

    - * Please note this value can be overridden by the {@link #setHttpProcessor( - * org.apache.http.protocol.HttpProcessor)} method. - */ - public final HttpClientBuilder setUserAgent(final String userAgent) { - this.userAgent = userAgent; - return this; - } - - /** - * Assigns default request header values. - *

    - * Please note this value can be overridden by the {@link #setHttpProcessor( - * org.apache.http.protocol.HttpProcessor)} method. - */ - public final HttpClientBuilder setDefaultHeaders(final Collection defaultHeaders) { - this.defaultHeaders = defaultHeaders; - return this; - } - - /** - * Adds this protocol interceptor to the head of the protocol processing list. - *

    - * Please note this value can be overridden by the {@link #setHttpProcessor( - * org.apache.http.protocol.HttpProcessor)} method. - */ - public final HttpClientBuilder addInterceptorFirst(final HttpResponseInterceptor itcp) { - if (itcp == null) { - return this; - } - if (responseFirst == null) { - responseFirst = new LinkedList(); - } - responseFirst.addFirst(itcp); - return this; - } - - /** - * Adds this protocol interceptor to the tail of the protocol processing list. - *

    - * Please note this value can be overridden by the {@link #setHttpProcessor( - * org.apache.http.protocol.HttpProcessor)} method. - */ - public final HttpClientBuilder addInterceptorLast(final HttpResponseInterceptor itcp) { - if (itcp == null) { - return this; - } - if (responseLast == null) { - responseLast = new LinkedList(); - } - responseLast.addLast(itcp); - return this; - } - - /** - * Adds this protocol interceptor to the head of the protocol processing list. - *

    - * Please note this value can be overridden by the {@link #setHttpProcessor( - * org.apache.http.protocol.HttpProcessor)} method. - */ - public final HttpClientBuilder addInterceptorFirst(final HttpRequestInterceptor itcp) { - if (itcp == null) { - return this; - } - if (requestFirst == null) { - requestFirst = new LinkedList(); - } - requestFirst.addFirst(itcp); - return this; - } - - /** - * Adds this protocol interceptor to the tail of the protocol processing list. - *

    - * Please note this value can be overridden by the {@link #setHttpProcessor( - * org.apache.http.protocol.HttpProcessor)} method. - */ - public final HttpClientBuilder addInterceptorLast(final HttpRequestInterceptor itcp) { - if (itcp == null) { - return this; - } - if (requestLast == null) { - requestLast = new LinkedList(); - } - requestLast.addLast(itcp); - return this; - } - - /** - * Disables state (cookie) management. - *

    - * Please note this value can be overridden by the {@link #setHttpProcessor( - * org.apache.http.protocol.HttpProcessor)} method. - */ - public final HttpClientBuilder disableCookieManagement() { - this.cookieManagementDisabled = true; - return this; - } - - /** - * Disables automatic content decompression. - *

    - * Please note this value can be overridden by the {@link #setHttpProcessor( - * org.apache.http.protocol.HttpProcessor)} method. - */ - public final HttpClientBuilder disableContentCompression() { - contentCompressionDisabled = true; - return this; - } - - /** - * Disables authentication scheme caching. - *

    - * Please note this value can be overridden by the {@link #setHttpProcessor( - * org.apache.http.protocol.HttpProcessor)} method. - */ - public final HttpClientBuilder disableAuthCaching() { - this.authCachingDisabled = true; - return this; - } - - /** - * Assigns {@link HttpProcessor} instance. - */ - public final HttpClientBuilder setHttpProcessor(final HttpProcessor httpprocessor) { - this.httpprocessor = httpprocessor; - return this; - } - - /** - * Assigns {@link HttpRequestRetryHandler} instance. - *

    - * Please note this value can be overridden by the {@link #disableAutomaticRetries()} - * method. - */ - public final HttpClientBuilder setRetryHandler(final HttpRequestRetryHandler retryHandler) { - this.retryHandler = retryHandler; - return this; - } - - /** - * Disables automatic request recovery and re-execution. - */ - public final HttpClientBuilder disableAutomaticRetries() { - automaticRetriesDisabled = true; - return this; - } - - /** - * Assigns default proxy value. - *

    - * Please note this value can be overridden by the {@link #setRoutePlanner( - * org.apache.http.conn.routing.HttpRoutePlanner)} method. - */ - public final HttpClientBuilder setProxy(final HttpHost proxy) { - this.proxy = proxy; - return this; - } - - /** - * Assigns {@link HttpRoutePlanner} instance. - */ - public final HttpClientBuilder setRoutePlanner(final HttpRoutePlanner routePlanner) { - this.routePlanner = routePlanner; - return this; - } - - /** - * Assigns {@link RedirectStrategy} instance. - *

    - * Please note this value can be overridden by the {@link #disableRedirectHandling()} - * method. -` */ - public final HttpClientBuilder setRedirectStrategy(final RedirectStrategy redirectStrategy) { - this.redirectStrategy = redirectStrategy; - return this; - } - - /** - * Disables automatic redirect handling. - */ - public final HttpClientBuilder disableRedirectHandling() { - redirectHandlingDisabled = true; - return this; - } - - /** - * Assigns {@link ConnectionBackoffStrategy} instance. - */ - public final HttpClientBuilder setConnectionBackoffStrategy( - final ConnectionBackoffStrategy connectionBackoffStrategy) { - this.connectionBackoffStrategy = connectionBackoffStrategy; - return this; - } - - /** - * Assigns {@link BackoffManager} instance. - */ - public final HttpClientBuilder setBackoffManager(final BackoffManager backoffManager) { - this.backoffManager = backoffManager; - return this; - } - - /** - * Assigns {@link ServiceUnavailableRetryStrategy} instance. - */ - public final HttpClientBuilder setServiceUnavailableRetryStrategy( - final ServiceUnavailableRetryStrategy serviceUnavailStrategy) { - this.serviceUnavailStrategy = serviceUnavailStrategy; - return this; - } - - /** - * Assigns default {@link CookieStore} instance which will be used for - * request execution if not explicitly set in the client execution context. - */ - public final HttpClientBuilder setDefaultCookieStore(final CookieStore cookieStore) { - this.cookieStore = cookieStore; - return this; - } - - /** - * Assigns default {@link CredentialsProvider} instance which will be used - * for request execution if not explicitly set in the client execution - * context. - */ - public final HttpClientBuilder setDefaultCredentialsProvider( - final CredentialsProvider credentialsProvider) { - this.credentialsProvider = credentialsProvider; - return this; - } - - /** - * Assigns default {@link org.apache.http.auth.AuthScheme} registry which will - * be used for request execution if not explicitly set in the client execution - * context. - */ - public final HttpClientBuilder setDefaultAuthSchemeRegistry( - final Lookup authSchemeRegistry) { - this.authSchemeRegistry = authSchemeRegistry; - return this; - } - - /** - * Assigns default {@link org.apache.http.cookie.CookieSpec} registry which will - * be used for request execution if not explicitly set in the client execution - * context. - */ - public final HttpClientBuilder setDefaultCookieSpecRegistry( - final Lookup cookieSpecRegistry) { - this.cookieSpecRegistry = cookieSpecRegistry; - return this; - } - - /** - * Assigns default {@link RequestConfig} instance which will be used - * for request execution if not explicitly set in the client execution - * context. - */ - public final HttpClientBuilder setDefaultRequestConfig(final RequestConfig config) { - this.defaultRequestConfig = config; - return this; - } - - /** - * Use system properties when creating and configuring default - * implementations. - */ - public final HttpClientBuilder useSystemProperties() { - systemProperties = true; - return this; - } - - /** - * For internal use. - */ - protected ClientExecChain decorateMainExec(final ClientExecChain mainExec) { - return mainExec; - } - - /** - * For internal use. - */ - protected ClientExecChain decorateProtocolExec(final ClientExecChain protocolExec) { - return protocolExec; - } - - /** - * For internal use. - */ - protected void addCloseable(final Closeable closeable) { - if (closeable == null) { - return; - } - if (closeables == null) { - closeables = new ArrayList(); - } - closeables.add(closeable); - } - - private static String[] split(final String s) { - if (TextUtils.isBlank(s)) { - return null; - } - return s.split(" *, *"); - } - - public CloseableHttpClient build() { - // Create main request executor - HttpRequestExecutor requestExec = this.requestExec; - if (requestExec == null) { - requestExec = new HttpRequestExecutor(); - } - HttpClientConnectionManager connManager = this.connManager; - if (connManager == null) { - LayeredConnectionSocketFactory sslSocketFactory = this.sslSocketFactory; - if (sslSocketFactory == null) { - final String[] supportedProtocols = systemProperties ? split( - System.getProperty("https.protocols")) : null; - final String[] supportedCipherSuites = systemProperties ? split( - System.getProperty("https.cipherSuites")) : null; - X509HostnameVerifier hostnameVerifier = this.hostnameVerifier; - if (hostnameVerifier == null) { - hostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER; - } - if (sslcontext != null) { - sslSocketFactory = new SSLConnectionSocketFactory( - sslcontext, supportedProtocols, supportedCipherSuites, hostnameVerifier); - } else { - if (systemProperties) { - sslSocketFactory = new SSLConnectionSocketFactory( - (SSLSocketFactory) SSLCertificateSocketFactory.getDefault(0), - supportedProtocols, supportedCipherSuites, hostnameVerifier); - } else { - sslSocketFactory = new SSLConnectionSocketFactory( - (SSLSocketFactory) SSLCertificateSocketFactory.getDefault(0), - hostnameVerifier); - } - } - } - @SuppressWarnings("resource") - final PoolingHttpClientConnectionManager poolingmgr = new PoolingHttpClientConnectionManager( - RegistryBuilder.create() - .register("http", PlainConnectionSocketFactory.getSocketFactory()) - .register("https", sslSocketFactory) - .build()); - if (defaultSocketConfig != null) { - poolingmgr.setDefaultSocketConfig(defaultSocketConfig); - } - if (defaultConnectionConfig != null) { - poolingmgr.setDefaultConnectionConfig(defaultConnectionConfig); - } - if (systemProperties) { - String s = System.getProperty("http.keepAlive", "true"); - if ("true".equalsIgnoreCase(s)) { - s = System.getProperty("http.maxConnections", "5"); - final int max = Integer.parseInt(s); - poolingmgr.setDefaultMaxPerRoute(max); - poolingmgr.setMaxTotal(2 * max); - } - } - if (maxConnTotal > 0) { - poolingmgr.setMaxTotal(maxConnTotal); - } - if (maxConnPerRoute > 0) { - poolingmgr.setDefaultMaxPerRoute(maxConnPerRoute); - } - connManager = poolingmgr; - } - ConnectionReuseStrategy reuseStrategy = this.reuseStrategy; - if (reuseStrategy == null) { - if (systemProperties) { - final String s = System.getProperty("http.keepAlive", "true"); - if ("true".equalsIgnoreCase(s)) { - reuseStrategy = DefaultConnectionReuseStrategyHC4.INSTANCE; - } else { - reuseStrategy = NoConnectionReuseStrategyHC4.INSTANCE; - } - } else { - reuseStrategy = DefaultConnectionReuseStrategyHC4.INSTANCE; - } - } - ConnectionKeepAliveStrategy keepAliveStrategy = this.keepAliveStrategy; - if (keepAliveStrategy == null) { - keepAliveStrategy = DefaultConnectionKeepAliveStrategyHC4.INSTANCE; - } - AuthenticationStrategy targetAuthStrategy = this.targetAuthStrategy; - if (targetAuthStrategy == null) { - targetAuthStrategy = TargetAuthenticationStrategy.INSTANCE; - } - AuthenticationStrategy proxyAuthStrategy = this.proxyAuthStrategy; - if (proxyAuthStrategy == null) { - proxyAuthStrategy = ProxyAuthenticationStrategy.INSTANCE; - } - UserTokenHandler userTokenHandler = this.userTokenHandler; - if (userTokenHandler == null) { - if (!connectionStateDisabled) { - userTokenHandler = DefaultUserTokenHandlerHC4.INSTANCE; - } else { - userTokenHandler = NoopUserTokenHandler.INSTANCE; - } - } - ClientExecChain execChain = new MainClientExec( - requestExec, - connManager, - reuseStrategy, - keepAliveStrategy, - targetAuthStrategy, - proxyAuthStrategy, - userTokenHandler); - - execChain = decorateMainExec(execChain); - - HttpProcessor httpprocessor = this.httpprocessor; - if (httpprocessor == null) { - - String userAgent = this.userAgent; - if (userAgent == null) { - if (systemProperties) { - userAgent = System.getProperty("http.agent"); - } - if (userAgent == null) { - userAgent = DEFAULT_USER_AGENT; - } - } - - final HttpProcessorBuilder b = HttpProcessorBuilder.create(); - if (requestFirst != null) { - for (final HttpRequestInterceptor i: requestFirst) { - b.addFirst(i); - } - } - if (responseFirst != null) { - for (final HttpResponseInterceptor i: responseFirst) { - b.addFirst(i); - } - } - b.addAll( - new RequestDefaultHeadersHC4(defaultHeaders), - new RequestContentHC4(), - new RequestTargetHostHC4(), - new RequestClientConnControl(), - new RequestUserAgentHC4(userAgent), - new RequestExpectContinue()); - if (!cookieManagementDisabled) { - b.add(new RequestAddCookiesHC4()); - } - if (!contentCompressionDisabled) { - b.add(new RequestAcceptEncoding()); - } - if (!authCachingDisabled) { - b.add(new RequestAuthCache()); - } - if (!cookieManagementDisabled) { - b.add(new ResponseProcessCookiesHC4()); - } - if (!contentCompressionDisabled) { - b.add(new ResponseContentEncoding()); - } - if (requestLast != null) { - for (final HttpRequestInterceptor i: requestLast) { - b.addLast(i); - } - } - if (responseLast != null) { - for (final HttpResponseInterceptor i: responseLast) { - b.addLast(i); - } - } - httpprocessor = b.build(); - } - execChain = new ProtocolExec(execChain, httpprocessor); - - execChain = decorateProtocolExec(execChain); - - // Add request retry executor, if not disabled - if (!automaticRetriesDisabled) { - HttpRequestRetryHandler retryHandler = this.retryHandler; - if (retryHandler == null) { - retryHandler = DefaultHttpRequestRetryHandlerHC4.INSTANCE; - } - execChain = new RetryExec(execChain, retryHandler); - } - - HttpRoutePlanner routePlanner = this.routePlanner; - if (routePlanner == null) { - SchemePortResolver schemePortResolver = this.schemePortResolver; - if (schemePortResolver == null) { - schemePortResolver = DefaultSchemePortResolver.INSTANCE; - } - if (proxy != null) { - routePlanner = new DefaultProxyRoutePlanner(proxy, schemePortResolver); - } else if (systemProperties) { - routePlanner = new SystemDefaultRoutePlanner( - schemePortResolver, ProxySelector.getDefault()); - } else { - routePlanner = new DefaultRoutePlanner(schemePortResolver); - } - } - // Add redirect executor, if not disabled - if (!redirectHandlingDisabled) { - RedirectStrategy redirectStrategy = this.redirectStrategy; - if (redirectStrategy == null) { - redirectStrategy = DefaultRedirectStrategy.INSTANCE; - } - execChain = new RedirectExec(execChain, routePlanner, redirectStrategy); - } - - // Optionally, add service unavailable retry executor - final ServiceUnavailableRetryStrategy serviceUnavailStrategy = this.serviceUnavailStrategy; - if (serviceUnavailStrategy != null) { - execChain = new ServiceUnavailableRetryExec(execChain, serviceUnavailStrategy); - } - // Optionally, add connection back-off executor - final BackoffManager backoffManager = this.backoffManager; - final ConnectionBackoffStrategy connectionBackoffStrategy = this.connectionBackoffStrategy; - if (backoffManager != null && connectionBackoffStrategy != null) { - execChain = new BackoffStrategyExec(execChain, connectionBackoffStrategy, backoffManager); - } - - Lookup authSchemeRegistry = this.authSchemeRegistry; - if (authSchemeRegistry == null) { - authSchemeRegistry = RegistryBuilder.create() - .register(AuthSchemes.BASIC, new BasicSchemeFactoryHC4()) - .register(AuthSchemes.DIGEST, new DigestSchemeFactoryHC4()) - .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) - .build(); - } - Lookup cookieSpecRegistry = this.cookieSpecRegistry; - if (cookieSpecRegistry == null) { - cookieSpecRegistry = RegistryBuilder.create() - .register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactoryHC4()) - .register(CookieSpecs.STANDARD, new RFC2965SpecFactoryHC4()) - .register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactoryHC4()) - .register(CookieSpecs.NETSCAPE, new NetscapeDraftSpecFactoryHC4()) - .register(CookieSpecs.IGNORE_COOKIES, new IgnoreSpecFactory()) - .register("rfc2109", new RFC2109SpecFactoryHC4()) - .register("rfc2965", new RFC2965SpecFactoryHC4()) - .build(); - } - - CookieStore defaultCookieStore = this.cookieStore; - if (defaultCookieStore == null) { - defaultCookieStore = new BasicCookieStoreHC4(); - } - - CredentialsProvider defaultCredentialsProvider = this.credentialsProvider; - if (defaultCredentialsProvider == null) { - if (systemProperties) { - defaultCredentialsProvider = new SystemDefaultCredentialsProvider(); - } else { - defaultCredentialsProvider = new BasicCredentialsProviderHC4(); - } - } - - return new InternalHttpClient( - execChain, - connManager, - routePlanner, - cookieSpecRegistry, - authSchemeRegistry, - defaultCookieStore, - defaultCredentialsProvider, - defaultRequestConfig != null ? defaultRequestConfig : RequestConfig.DEFAULT, - closeables != null ? new ArrayList(closeables) : null); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/HttpClients.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/HttpClients.java deleted file mode 100644 index 569b047a..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/HttpClients.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import org.apache.http.annotation.Immutable; -import org.apache.http.conn.HttpClientConnectionManager; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; - -/** - * Factory methods for {@link CloseableHttpClient} instances. - * @since 4.3 - */ -@Immutable -public class HttpClients { - - private HttpClients() { - super(); - } - - /** - * Creates builder object for construction of custom - * {@link CloseableHttpClient} instances. - */ - public static HttpClientBuilder custom() { - return HttpClientBuilder.create(); - } - - /** - * Creates {@link CloseableHttpClient} instance with default - * configuration. - */ - public static CloseableHttpClient createDefault() { - return HttpClientBuilder.create().build(); - } - - /** - * Creates {@link CloseableHttpClient} instance with default - * configuration based on ssytem properties. - */ - public static CloseableHttpClient createSystem() { - return HttpClientBuilder.create().useSystemProperties().build(); - } - - /** - * Creates {@link CloseableHttpClient} instance that implements - * the most basic HTTP protocol support. - */ - public static CloseableHttpClient createMinimal() { - return new MinimalHttpClient(new PoolingHttpClientConnectionManager()); - } - - /** - * Creates {@link CloseableHttpClient} instance that implements - * the most basic HTTP protocol support. - */ - public static CloseableHttpClient createMinimal(final HttpClientConnectionManager connManager) { - return new MinimalHttpClient(connManager); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/HttpRequestFutureTask.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/HttpRequestFutureTask.java deleted file mode 100644 index f37cd7a9..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/HttpRequestFutureTask.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.client; - -import java.util.concurrent.FutureTask; - -import org.apache.http.client.methods.HttpUriRequest; - -/** - * FutureTask implementation that wraps a HttpAsyncClientCallable and exposes various task - * specific metrics. - * - * @param - */ -public class HttpRequestFutureTask extends FutureTask { - - private final HttpUriRequest request; - private final HttpRequestTaskCallable callable; - - public HttpRequestFutureTask( - final HttpUriRequest request, - final HttpRequestTaskCallable httpCallable) { - super(httpCallable); - this.request = request; - this.callable = httpCallable; - } - - /* - * (non-Javadoc) - * @see java.util.concurrent.FutureTask#cancel(boolean) - */ - @Override - public boolean cancel(final boolean mayInterruptIfRunning) { - callable.cancel(); - if (mayInterruptIfRunning) { - request.abort(); - } - return super.cancel(mayInterruptIfRunning); - } - - /** - * @return the time in millis the task was scheduled. - */ - public long scheduledTime() { - return callable.getScheduled(); - } - - /** - * @return the time in millis the task was started. - */ - public long startedTime() { - return callable.getStarted(); - } - - /** - * @return the time in millis the task was finished/cancelled. - */ - public long endedTime() { - if (isDone()) { - return callable.getEnded(); - } else { - throw new IllegalStateException("Task is not done yet"); - } - } - - /** - * @return the time in millis it took to make the request (excluding the time it was - * scheduled to be executed). - */ - public long requestDuration() { - if (isDone()) { - return endedTime() - startedTime(); - } else { - throw new IllegalStateException("Task is not done yet"); - } - } - - /** - * @return the time in millis it took to execute the task from the moment it was scheduled. - */ - public long taskDuration() { - if (isDone()) { - return endedTime() - scheduledTime(); - } else { - throw new IllegalStateException("Task is not done yet"); - } - } - - @Override - public String toString() { - return request.getRequestLine().getUri(); - } - -} \ No newline at end of file diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/HttpRequestTaskCallable.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/HttpRequestTaskCallable.java deleted file mode 100644 index a4577b55..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/HttpRequestTaskCallable.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.client; - -import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.http.client.HttpClient; -import org.apache.http.client.ResponseHandler; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.concurrent.FutureCallback; -import org.apache.http.protocol.HttpContext; - -class HttpRequestTaskCallable implements Callable { - - private final HttpUriRequest request; - private final HttpClient httpclient; - private final AtomicBoolean cancelled = new AtomicBoolean(false); - - private final long scheduled = System.currentTimeMillis(); - private long started = -1; - private long ended = -1; - - private final HttpContext context; - private final ResponseHandler responseHandler; - private final FutureCallback callback; - - private final FutureRequestExecutionMetrics metrics; - - HttpRequestTaskCallable( - final HttpClient httpClient, - final HttpUriRequest request, - final HttpContext context, - final ResponseHandler responseHandler, - final FutureCallback callback, - final FutureRequestExecutionMetrics metrics) { - this.httpclient = httpClient; - this.responseHandler = responseHandler; - this.request = request; - this.context = context; - this.callback = callback; - this.metrics = metrics; - } - - public long getScheduled() { - return scheduled; - } - - public long getStarted() { - return started; - } - - public long getEnded() { - return ended; - } - - public V call() throws Exception { - if (!cancelled.get()) { - try { - metrics.getActiveConnections().incrementAndGet(); - started = System.currentTimeMillis(); - try { - metrics.getScheduledConnections().decrementAndGet(); - final V result = httpclient.execute(request, responseHandler, context); - ended = System.currentTimeMillis(); - metrics.getSuccessfulConnections().increment(started); - if (callback != null) { - callback.completed(result); - } - return result; - } catch (final Exception e) { - metrics.getFailedConnections().increment(started); - ended = System.currentTimeMillis(); - if (callback != null) { - callback.failed(e); - } - throw e; - } - } finally { - metrics.getRequests().increment(started); - metrics.getTasks().increment(started); - metrics.getActiveConnections().decrementAndGet(); - } - } else { - throw new IllegalStateException("call has been cancelled for request " + request.getURI()); - } - } - - public void cancel() { - cancelled.set(true); - if (callback != null) { - callback.cancelled(); - } - } -} \ No newline at end of file diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/InternalHttpClient.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/InternalHttpClient.java deleted file mode 100644 index dd1304c9..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/InternalHttpClient.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.io.Closeable; -import java.io.IOException; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import android.util.Log; - -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.auth.AuthSchemeProvider; -import org.apache.http.auth.AuthStateHC4; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.CookieStore; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.Configurable; -import org.apache.http.client.methods.HttpExecutionAware; -import org.apache.http.client.methods.HttpRequestWrapper; -import org.apache.http.client.params.ClientPNames; -import org.apache.http.client.params.HttpClientParamConfig; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.config.Lookup; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.ClientConnectionRequest; -import org.apache.http.conn.HttpClientConnectionManager; -import org.apache.http.conn.ManagedClientConnection; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.conn.routing.HttpRoutePlanner; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.cookie.CookieSpecProvider; -import org.apache.http.impl.execchain.ClientExecChain; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpParamsNames; -import org.apache.http.protocol.BasicHttpContextHC4; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; - -/** - * Internal class. - * - * @since 4.3 - */ -@ThreadSafe -@SuppressWarnings("deprecation") -class InternalHttpClient extends CloseableHttpClient { - - private final static String TAG = "HttpClient"; - - private final ClientExecChain execChain; - private final HttpClientConnectionManager connManager; - private final HttpRoutePlanner routePlanner; - private final Lookup cookieSpecRegistry; - private final Lookup authSchemeRegistry; - private final CookieStore cookieStore; - private final CredentialsProvider credentialsProvider; - private final RequestConfig defaultConfig; - private final List closeables; - - public InternalHttpClient( - final ClientExecChain execChain, - final HttpClientConnectionManager connManager, - final HttpRoutePlanner routePlanner, - final Lookup cookieSpecRegistry, - final Lookup authSchemeRegistry, - final CookieStore cookieStore, - final CredentialsProvider credentialsProvider, - final RequestConfig defaultConfig, - final List closeables) { - super(); - Args.notNull(execChain, "HTTP client exec chain"); - Args.notNull(connManager, "HTTP connection manager"); - Args.notNull(routePlanner, "HTTP route planner"); - this.execChain = execChain; - this.connManager = connManager; - this.routePlanner = routePlanner; - this.cookieSpecRegistry = cookieSpecRegistry; - this.authSchemeRegistry = authSchemeRegistry; - this.cookieStore = cookieStore; - this.credentialsProvider = credentialsProvider; - this.defaultConfig = defaultConfig; - this.closeables = closeables; - } - - private HttpRoute determineRoute( - final HttpHost target, - final HttpRequest request, - final HttpContext context) throws HttpException { - HttpHost host = target; - if (host == null) { - host = (HttpHost) request.getParams().getParameter(ClientPNames.DEFAULT_HOST); - } - return this.routePlanner.determineRoute(host, request, context); - } - - private void setupContext(final HttpClientContext context) { - if (context.getAttribute(HttpClientContext.TARGET_AUTH_STATE) == null) { - context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, new AuthStateHC4()); - } - if (context.getAttribute(HttpClientContext.PROXY_AUTH_STATE) == null) { - context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, new AuthStateHC4()); - } - if (context.getAttribute(HttpClientContext.AUTHSCHEME_REGISTRY) == null) { - context.setAttribute(HttpClientContext.AUTHSCHEME_REGISTRY, this.authSchemeRegistry); - } - if (context.getAttribute(HttpClientContext.COOKIESPEC_REGISTRY) == null) { - context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); - } - if (context.getAttribute(HttpClientContext.COOKIE_STORE) == null) { - context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); - } - if (context.getAttribute(HttpClientContext.CREDS_PROVIDER) == null) { - context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credentialsProvider); - } - if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) { - context.setAttribute(HttpClientContext.REQUEST_CONFIG, this.defaultConfig); - } - } - - @Override - protected CloseableHttpResponse doExecute( - final HttpHost target, - final HttpRequest request, - final HttpContext context) throws IOException, ClientProtocolException { - Args.notNull(request, "HTTP request"); - HttpExecutionAware execAware = null; - if (request instanceof HttpExecutionAware) { - execAware = (HttpExecutionAware) request; - } - try { - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(request); - final HttpClientContext localcontext = HttpClientContext.adapt( - context != null ? context : new BasicHttpContextHC4()); - RequestConfig config = null; - if (request instanceof Configurable) { - config = ((Configurable) request).getConfig(); - } - if (config == null) { - final HttpParams params = request.getParams(); - config = HttpClientParamConfig.getRequestConfig(params); - } - if (config != null) { - localcontext.setRequestConfig(config); - } - setupContext(localcontext); - final HttpRoute route = determineRoute(target, wrapper, localcontext); - return this.execChain.execute(route, wrapper, localcontext, execAware); - } catch (final HttpException httpException) { - throw new ClientProtocolException(httpException); - } - } - - public void close() { - this.connManager.shutdown(); - if (this.closeables != null) { - for (final Closeable closeable: this.closeables) { - try { - closeable.close(); - } catch (final IOException ex) { - Log.e(TAG, ex.getMessage(), ex); - } - } - } - } - - public HttpParams getParams() { - throw new UnsupportedOperationException(); - } - - public ClientConnectionManager getConnectionManager() { - - return new ClientConnectionManager() { - - public void shutdown() { - connManager.shutdown(); - } - - public ClientConnectionRequest requestConnection( - final HttpRoute route, final Object state) { - throw new UnsupportedOperationException(); - } - - public void releaseConnection( - final ManagedClientConnection conn, - final long validDuration, final TimeUnit timeUnit) { - throw new UnsupportedOperationException(); - } - - public SchemeRegistry getSchemeRegistry() { - throw new UnsupportedOperationException(); - } - - public void closeIdleConnections(final long idletime, final TimeUnit tunit) { - connManager.closeIdleConnections(idletime, tunit); - } - - public void closeExpiredConnections() { - connManager.closeExpiredConnections(); - } - - }; - - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/LaxRedirectStrategy.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/LaxRedirectStrategy.java deleted file mode 100644 index f4585916..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/LaxRedirectStrategy.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import org.apache.http.annotation.Immutable; -import org.apache.http.client.methods.HttpGetHC4; -import org.apache.http.client.methods.HttpHeadHC4; -import org.apache.http.client.methods.HttpPostHC4; - -/** - * Lax {@link org.apache.http.client.RedirectStrategy} implementation - * that automatically redirects all HEAD, GET and POST requests. - * This strategy relaxes restrictions on automatic redirection of - * POST methods imposed by the HTTP specification. - * - * @since 4.2 - */ -@Immutable -public class LaxRedirectStrategy extends DefaultRedirectStrategy { - - /** - * Redirectable methods. - */ - private static final String[] REDIRECT_METHODS = new String[] { - HttpGetHC4.METHOD_NAME, - HttpPostHC4.METHOD_NAME, - HttpHeadHC4.METHOD_NAME - }; - - @Override - protected boolean isRedirectable(final String method) { - for (final String m: REDIRECT_METHODS) { - if (m.equalsIgnoreCase(method)) { - return true; - } - } - return false; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/MinimalHttpClient.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/MinimalHttpClient.java deleted file mode 100644 index 48a71c52..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/MinimalHttpClient.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.Configurable; -import org.apache.http.client.methods.HttpExecutionAware; -import org.apache.http.client.methods.HttpRequestWrapper; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.ClientConnectionRequest; -import org.apache.http.conn.HttpClientConnectionManager; -import org.apache.http.conn.ManagedClientConnection; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.impl.DefaultConnectionReuseStrategyHC4; -import org.apache.http.impl.execchain.MinimalClientExec; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.BasicHttpContextHC4; -import org.apache.http.protocol.HttpContext; -import org.apache.http.protocol.HttpRequestExecutor; -import org.apache.http.util.Args; - -/** - * Internal class. - * - * @since 4.3 - */ -@ThreadSafe -@SuppressWarnings("deprecation") -class MinimalHttpClient extends CloseableHttpClient { - - private final HttpClientConnectionManager connManager; - private final MinimalClientExec requestExecutor; - private final HttpParams params; - - public MinimalHttpClient( - final HttpClientConnectionManager connManager) { - super(); - this.connManager = Args.notNull(connManager, "HTTP connection manager"); - this.requestExecutor = new MinimalClientExec( - new HttpRequestExecutor(), - connManager, - DefaultConnectionReuseStrategyHC4.INSTANCE, - DefaultConnectionKeepAliveStrategyHC4.INSTANCE); - this.params = new BasicHttpParams(); - } - - @Override - protected CloseableHttpResponse doExecute( - final HttpHost target, - final HttpRequest request, - final HttpContext context) throws IOException, ClientProtocolException { - Args.notNull(target, "Target host"); - Args.notNull(request, "HTTP request"); - HttpExecutionAware execAware = null; - if (request instanceof HttpExecutionAware) { - execAware = (HttpExecutionAware) request; - } - try { - final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(request); - final HttpClientContext localcontext = HttpClientContext.adapt( - context != null ? context : new BasicHttpContextHC4()); - final HttpRoute route = new HttpRoute(target); - RequestConfig config = null; - if (request instanceof Configurable) { - config = ((Configurable) request).getConfig(); - } - if (config != null) { - localcontext.setRequestConfig(config); - } - return this.requestExecutor.execute(route, wrapper, localcontext, execAware); - } catch (final HttpException httpException) { - throw new ClientProtocolException(httpException); - } - } - - public HttpParams getParams() { - return this.params; - } - - public void close() { - this.connManager.shutdown(); - } - - public ClientConnectionManager getConnectionManager() { - - return new ClientConnectionManager() { - - public void shutdown() { - connManager.shutdown(); - } - - public ClientConnectionRequest requestConnection( - final HttpRoute route, final Object state) { - throw new UnsupportedOperationException(); - } - - public void releaseConnection( - final ManagedClientConnection conn, - final long validDuration, final TimeUnit timeUnit) { - throw new UnsupportedOperationException(); - } - - public SchemeRegistry getSchemeRegistry() { - throw new UnsupportedOperationException(); - } - - public void closeIdleConnections(final long idletime, final TimeUnit tunit) { - connManager.closeIdleConnections(idletime, tunit); - } - - public void closeExpiredConnections() { - connManager.closeExpiredConnections(); - } - - }; - - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/NoopUserTokenHandler.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/NoopUserTokenHandler.java deleted file mode 100644 index 62765515..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/NoopUserTokenHandler.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.client; - -import org.apache.http.annotation.Immutable; -import org.apache.http.client.UserTokenHandler; -import org.apache.http.protocol.HttpContext; - -/** - * Noop implementation of {@link UserTokenHandler} that always returns null. - * - * @since 4.3 - */ -@Immutable -public class NoopUserTokenHandler implements UserTokenHandler { - - public static final NoopUserTokenHandler INSTANCE = new NoopUserTokenHandler(); - - public Object getUserToken(final HttpContext context) { - return null; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/NullBackoffStrategy.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/NullBackoffStrategy.java deleted file mode 100644 index 0c7a452e..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/NullBackoffStrategy.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.client; - -import org.apache.http.HttpResponse; -import org.apache.http.client.ConnectionBackoffStrategy; - -/** - * This is a {@link ConnectionBackoffStrategy} that never backs off, - * for compatibility with existing behavior. - * - * @since 4.2 - */ -public class NullBackoffStrategy implements ConnectionBackoffStrategy { - - public boolean shouldBackoff(final Throwable t) { - return false; - } - - public boolean shouldBackoff(final HttpResponse resp) { - return false; - } -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/ProxyAuthenticationStrategy.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/ProxyAuthenticationStrategy.java deleted file mode 100644 index 49e6e912..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/ProxyAuthenticationStrategy.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.util.Collection; - -import org.apache.http.HttpStatus; -import org.apache.http.annotation.Immutable; -import org.apache.http.auth.AUTH; -import org.apache.http.client.config.RequestConfig; - -/** - * Default {@link org.apache.http.client.AuthenticationStrategy} implementation - * for proxy host authentication. - * - * @since 4.2 - */ -@Immutable -public class ProxyAuthenticationStrategy extends AuthenticationStrategyImpl { - - public static final ProxyAuthenticationStrategy INSTANCE = new ProxyAuthenticationStrategy(); - - public ProxyAuthenticationStrategy() { - super(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED, AUTH.PROXY_AUTH); - } - - @Override - Collection getPreferredAuthSchemes(final RequestConfig config) { - return config.getProxyPreferredAuthSchemes(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/ProxyClient.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/ProxyClient.java deleted file mode 100644 index 6e8a5ec6..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/ProxyClient.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.io.IOException; -import java.net.Socket; - -import org.apache.http.ConnectionReuseStrategy; -import org.apache.http.HttpEntity; -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.HttpVersion; -import org.apache.http.auth.AUTH; -import org.apache.http.auth.AuthSchemeRegistry; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.AuthStateHC4; -import org.apache.http.auth.Credentials; -import org.apache.http.client.config.AuthSchemes; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.params.HttpClientParamConfig; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.client.protocol.RequestClientConnControl; -import org.apache.http.config.ConnectionConfig; -import org.apache.http.conn.HttpConnectionFactory; -import org.apache.http.conn.ManagedHttpClientConnection; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.conn.routing.RouteInfo.LayerType; -import org.apache.http.conn.routing.RouteInfo.TunnelType; -import org.apache.http.entity.BufferedHttpEntityHC4; -import org.apache.http.impl.DefaultConnectionReuseStrategyHC4; -import org.apache.http.impl.auth.BasicSchemeFactoryHC4; -import org.apache.http.impl.auth.DigestSchemeFactoryHC4; -import org.apache.http.impl.auth.HttpAuthenticator; -import org.apache.http.impl.auth.NTLMSchemeFactory; -import org.apache.http.impl.conn.ManagedHttpClientConnectionFactory; -import org.apache.http.impl.execchain.TunnelRefusedException; -import org.apache.http.message.BasicHttpRequest; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpParamConfig; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.BasicHttpContextHC4; -import org.apache.http.protocol.HttpContext; -import org.apache.http.protocol.HttpCoreContext; -import org.apache.http.protocol.HttpProcessor; -import org.apache.http.protocol.HttpRequestExecutor; -import org.apache.http.protocol.ImmutableHttpProcessor; -import org.apache.http.protocol.RequestTargetHostHC4; -import org.apache.http.protocol.RequestUserAgentHC4; -import org.apache.http.util.Args; -import org.apache.http.util.EntityUtilsHC4; - -/** - * ProxyClient can be used to establish a tunnel via an HTTP proxy. - */ -@SuppressWarnings("deprecation") -public class ProxyClient { - - private final HttpConnectionFactory connFactory; - private final ConnectionConfig connectionConfig; - private final RequestConfig requestConfig; - private final HttpProcessor httpProcessor; - private final HttpRequestExecutor requestExec; - private final ProxyAuthenticationStrategy proxyAuthStrategy; - private final HttpAuthenticator authenticator; - private final AuthStateHC4 proxyAuthState; - private final AuthSchemeRegistry authSchemeRegistry; - private final ConnectionReuseStrategy reuseStrategy; - - /** - * @since 4.3 - */ - public ProxyClient( - final HttpConnectionFactory connFactory, - final ConnectionConfig connectionConfig, - final RequestConfig requestConfig) { - super(); - this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE; - this.connectionConfig = connectionConfig != null ? connectionConfig : ConnectionConfig.DEFAULT; - this.requestConfig = requestConfig != null ? requestConfig : RequestConfig.DEFAULT; - this.httpProcessor = new ImmutableHttpProcessor( - new RequestTargetHostHC4(), new RequestClientConnControl(), new RequestUserAgentHC4()); - this.requestExec = new HttpRequestExecutor(); - this.proxyAuthStrategy = new ProxyAuthenticationStrategy(); - this.authenticator = new HttpAuthenticator(); - this.proxyAuthState = new AuthStateHC4(); - this.authSchemeRegistry = new AuthSchemeRegistry(); - this.authSchemeRegistry.register(AuthSchemes.BASIC, new BasicSchemeFactoryHC4()); - this.authSchemeRegistry.register(AuthSchemes.DIGEST, new DigestSchemeFactoryHC4()); - this.authSchemeRegistry.register(AuthSchemes.NTLM, new NTLMSchemeFactory()); - this.reuseStrategy = new DefaultConnectionReuseStrategyHC4(); - } - - /** - * @deprecated (4.3) use {@link ProxyClient#ProxyClient(HttpConnectionFactory, ConnectionConfig, RequestConfig)} - */ - @Deprecated - public ProxyClient(final HttpParams params) { - this(null, - HttpParamConfig.getConnectionConfig(params), - HttpClientParamConfig.getRequestConfig(params)); - } - - /** - * @since 4.3 - */ - public ProxyClient(final RequestConfig requestConfig) { - this(null, null, requestConfig); - } - - public ProxyClient() { - this(null, null, null); - } - - /** - * @deprecated (4.3) do not use. - */ - @Deprecated - public HttpParams getParams() { - return new BasicHttpParams(); - } - - /** - * @deprecated (4.3) do not use. - */ - @Deprecated - public AuthSchemeRegistry getAuthSchemeRegistry() { - return this.authSchemeRegistry; - } - - public Socket tunnel( - final HttpHost proxy, - final HttpHost target, - final Credentials credentials) throws IOException, HttpException { - Args.notNull(proxy, "Proxy host"); - Args.notNull(target, "Target host"); - Args.notNull(credentials, "Credentials"); - HttpHost host = target; - if (host.getPort() <= 0) { - host = new HttpHost(host.getHostName(), 80, host.getSchemeName()); - } - final HttpRoute route = new HttpRoute( - host, - this.requestConfig.getLocalAddress(), - proxy, false, TunnelType.TUNNELLED, LayerType.PLAIN); - - final ManagedHttpClientConnection conn = this.connFactory.create( - route, this.connectionConfig); - final HttpContext context = new BasicHttpContextHC4(); - HttpResponse response; - - final HttpRequest connect = new BasicHttpRequest( - "CONNECT", host.toHostString(), HttpVersion.HTTP_1_1); - - final BasicCredentialsProviderHC4 credsProvider = new BasicCredentialsProviderHC4(); - credsProvider.setCredentials(new AuthScope(proxy.getHostName(), proxy.getPort()), credentials); - - // Populate the execution context - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); - context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn); - context.setAttribute(HttpCoreContext.HTTP_REQUEST, connect); - context.setAttribute(HttpClientContext.HTTP_ROUTE, route); - context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, this.proxyAuthState); - context.setAttribute(HttpClientContext.CREDS_PROVIDER, credsProvider); - context.setAttribute(HttpClientContext.AUTHSCHEME_REGISTRY, this.authSchemeRegistry); - context.setAttribute(HttpClientContext.REQUEST_CONFIG, this.requestConfig); - - this.requestExec.preProcess(connect, this.httpProcessor, context); - - for (;;) { - if (!conn.isOpen()) { - final Socket socket = new Socket(proxy.getHostName(), proxy.getPort()); - conn.bind(socket); - } - - this.authenticator.generateAuthResponse(connect, this.proxyAuthState, context); - - response = this.requestExec.execute(connect, conn, context); - - final int status = response.getStatusLine().getStatusCode(); - if (status < 200) { - throw new HttpException("Unexpected response to CONNECT request: " + - response.getStatusLine()); - } - if (this.authenticator.isAuthenticationRequested(proxy, response, - this.proxyAuthStrategy, this.proxyAuthState, context)) { - if (this.authenticator.handleAuthChallenge(proxy, response, - this.proxyAuthStrategy, this.proxyAuthState, context)) { - // Retry request - if (this.reuseStrategy.keepAlive(response, context)) { - // Consume response content - final HttpEntity entity = response.getEntity(); - EntityUtilsHC4.consume(entity); - } else { - conn.close(); - } - // discard previous auth header - connect.removeHeaders(AUTH.PROXY_AUTH_RESP); - } else { - break; - } - } else { - break; - } - } - - final int status = response.getStatusLine().getStatusCode(); - - if (status > 299) { - - // Buffer response content - final HttpEntity entity = response.getEntity(); - if (entity != null) { - response.setEntity(new BufferedHttpEntityHC4(entity)); - } - - conn.close(); - throw new TunnelRefusedException("CONNECT refused by proxy: " + - response.getStatusLine(), response); - } - return conn.getSocket(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/RedirectLocationsHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/RedirectLocationsHC4.java deleted file mode 100644 index 6702147e..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/RedirectLocationsHC4.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.net.URI; -import java.util.AbstractList; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.apache.http.annotation.NotThreadSafe; - -/** - * This class represents a collection of {@link java.net.URI}s used - * as redirect locations. - * - * @since 4.0 - */ -@NotThreadSafe // HashSet/ArrayList are not synch. -public class RedirectLocationsHC4 extends AbstractList { - - private final Set unique; - private final List all; - - public RedirectLocationsHC4() { - super(); - this.unique = new HashSet(); - this.all = new ArrayList(); - } - - /** - * Test if the URI is present in the collection. - */ - public boolean contains(final URI uri) { - return this.unique.contains(uri); - } - - /** - * Adds a new URI to the collection. - */ - public void add(final URI uri) { - this.unique.add(uri); - this.all.add(uri); - } - - /** - * Removes a URI from the collection. - */ - public boolean remove(final URI uri) { - final boolean removed = this.unique.remove(uri); - if (removed) { - final Iterator it = this.all.iterator(); - while (it.hasNext()) { - final URI current = it.next(); - if (current.equals(uri)) { - it.remove(); - } - } - } - return removed; - } - - /** - * Returns all redirect {@link URI}s in the order they were added to the collection. - * - * @return list of all URIs - * - * @since 4.1 - */ - public List getAll() { - return new ArrayList(this.all); - } - - /** - * Returns the URI at the specified position in this list. - * - * @param index - * index of the location to return - * @return the URI at the specified position in this list - * @throws IndexOutOfBoundsException - * if the index is out of range ( - * index < 0 || index >= size()) - * @since 4.3 - */ - @Override - public URI get(final int index) { - return this.all.get(index); - } - - /** - * Returns the number of elements in this list. If this list contains more - * than Integer.MAX_VALUE elements, returns - * Integer.MAX_VALUE. - * - * @return the number of elements in this list - * @since 4.3 - */ - @Override - public int size() { - return this.all.size(); - } - - /** - * Replaces the URI at the specified position in this list with the - * specified element (must be a URI). - * - * @param index - * index of the element to replace - * @param element - * URI to be stored at the specified position - * @return the URI previously at the specified position - * @throws UnsupportedOperationException - * if the set operation is not supported by this list - * @throws ClassCastException - * if the element is not a {@link URI} - * @throws NullPointerException - * if the specified element is null and this list does not - * permit null elements - * @throws IndexOutOfBoundsException - * if the index is out of range ( - * index < 0 || index >= size()) - * @since 4.3 - */ - @Override - public Object set(final int index, final Object element) { - final URI removed = this.all.set(index, (URI) element); - this.unique.remove(removed); - this.unique.add((URI) element); - if (this.all.size() != this.unique.size()) { - this.unique.addAll(this.all); - } - return removed; - } - - /** - * Inserts the specified element at the specified position in this list - * (must be a URI). Shifts the URI currently at that position (if any) and - * any subsequent URIs to the right (adds one to their indices). - * - * @param index - * index at which the specified element is to be inserted - * @param element - * URI to be inserted - * @throws UnsupportedOperationException - * if the add operation is not supported by this list - * @throws ClassCastException - * if the element is not a {@link URI} - * @throws NullPointerException - * if the specified element is null and this list does not - * permit null elements - * @throws IndexOutOfBoundsException - * if the index is out of range ( - * index < 0 || index > size()) - * @since 4.3 - */ - @Override - public void add(final int index, final Object element) { - this.all.add(index, (URI) element); - this.unique.add((URI) element); - } - - /** - * Removes the URI at the specified position in this list. Shifts any - * subsequent URIs to the left (subtracts one from their indices). Returns - * the URI that was removed from the list. - * - * @param index - * the index of the URI to be removed - * @return the URI previously at the specified position - * @throws IndexOutOfBoundsException - * if the index is out of range ( - * index < 0 || index >= size()) - * @since 4.3 - */ - @Override - public URI remove(final int index) { - final URI removed = this.all.remove(index); - this.unique.remove(removed); - if (this.all.size() != this.unique.size()) { - this.unique.addAll(this.all); - } - return removed; - } - - /** - * Returns true if this collection contains the specified element. - * More formally, returns true if and only if this collection - * contains at least one element e such that - * (o==null ? e==null : o.equals(e)). - * - * @param o element whose presence in this collection is to be tested - * @return true if this collection contains the specified - * element - */ - @Override - public boolean contains(final Object o) { - return this.unique.contains(o); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/StandardHttpRequestRetryHandler.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/StandardHttpRequestRetryHandler.java deleted file mode 100644 index bc05a141..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/StandardHttpRequestRetryHandler.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.http.HttpRequest; -import org.apache.http.annotation.Immutable; - -/** - * {@link org.apache.http.client.HttpRequestRetryHandler} which assumes - * that all requested HTTP methods which should be idempotent according - * to RFC-2616 are in fact idempotent and can be retried. - *

    - * According to RFC-2616 section 9.1.2 the idempotent HTTP methods are: - * GET, HEAD, PUT, DELETE, OPTIONS, and TRACE - * - * @since 4.2 - */ -@Immutable -public class StandardHttpRequestRetryHandler extends DefaultHttpRequestRetryHandlerHC4 { - - private final Map idempotentMethods; - - /** - * Default constructor - */ - public StandardHttpRequestRetryHandler(final int retryCount, final boolean requestSentRetryEnabled) { - super(retryCount, requestSentRetryEnabled); - this.idempotentMethods = new ConcurrentHashMap(); - this.idempotentMethods.put("GET", Boolean.TRUE); - this.idempotentMethods.put("HEAD", Boolean.TRUE); - this.idempotentMethods.put("PUT", Boolean.TRUE); - this.idempotentMethods.put("DELETE", Boolean.TRUE); - this.idempotentMethods.put("OPTIONS", Boolean.TRUE); - this.idempotentMethods.put("TRACE", Boolean.TRUE); - } - - /** - * Default constructor - */ - public StandardHttpRequestRetryHandler() { - this(3, false); - } - - @Override - protected boolean handleAsIdempotent(final HttpRequest request) { - final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); - final Boolean b = this.idempotentMethods.get(method); - return b != null && b.booleanValue(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/SystemClock.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/SystemClock.java deleted file mode 100644 index cc62de3f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/SystemClock.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.client; - -/** - * The actual system clock. - * - * @since 4.2 - */ -class SystemClock implements Clock { - - public long getCurrentTime() { - return System.currentTimeMillis(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/SystemDefaultCredentialsProvider.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/SystemDefaultCredentialsProvider.java deleted file mode 100644 index 01cde796..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/SystemDefaultCredentialsProvider.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.client; - -import java.net.Authenticator; -import java.net.PasswordAuthentication; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.Credentials; -import org.apache.http.auth.NTCredentials; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.config.AuthSchemes; -import org.apache.http.util.Args; - -/** - * Implementation of {@link CredentialsProvider} backed by standard - * JRE {@link Authenticator}. - * - * @since 4.3 - */ -@ThreadSafe -public class SystemDefaultCredentialsProvider implements CredentialsProvider { - - private static final Map SCHEME_MAP; - - static { - SCHEME_MAP = new ConcurrentHashMap(); - SCHEME_MAP.put(AuthSchemes.BASIC.toUpperCase(Locale.ENGLISH), "Basic"); - SCHEME_MAP.put(AuthSchemes.DIGEST.toUpperCase(Locale.ENGLISH), "Digest"); - SCHEME_MAP.put(AuthSchemes.NTLM.toUpperCase(Locale.ENGLISH), "NTLM"); - SCHEME_MAP.put(AuthSchemes.SPNEGO.toUpperCase(Locale.ENGLISH), "SPNEGO"); - SCHEME_MAP.put(AuthSchemes.KERBEROS.toUpperCase(Locale.ENGLISH), "Kerberos"); - } - - private static String translateScheme(final String key) { - if (key == null) { - return null; - } - final String s = SCHEME_MAP.get(key); - return s != null ? s : key; - } - - private final BasicCredentialsProviderHC4 internal; - - /** - * Default constructor. - */ - public SystemDefaultCredentialsProvider() { - super(); - this.internal = new BasicCredentialsProviderHC4(); - } - - public void setCredentials(final AuthScope authscope, final Credentials credentials) { - internal.setCredentials(authscope, credentials); - } - - private static PasswordAuthentication getSystemCreds( - final AuthScope authscope, - final Authenticator.RequestorType requestorType) { - final String hostname = authscope.getHost(); - final int port = authscope.getPort(); - final String protocol = port == 443 ? "https" : "http"; - return Authenticator.requestPasswordAuthentication( - hostname, - null, - port, - protocol, - null, - translateScheme(authscope.getScheme()), - null, - requestorType); - } - - public Credentials getCredentials(final AuthScope authscope) { - Args.notNull(authscope, "Auth scope"); - final Credentials localcreds = internal.getCredentials(authscope); - if (localcreds != null) { - return localcreds; - } - if (authscope.getHost() != null) { - PasswordAuthentication systemcreds = getSystemCreds( - authscope, Authenticator.RequestorType.SERVER); - if (systemcreds == null) { - systemcreds = getSystemCreds( - authscope, Authenticator.RequestorType.PROXY); - } - if (systemcreds != null) { - final String domain = System.getProperty("http.auth.ntlm.domain"); - if (domain != null) { - return new NTCredentials( - systemcreds.getUserName(), - new String(systemcreds.getPassword()), - null, domain); - } else { - if (AuthSchemes.NTLM.equalsIgnoreCase(authscope.getScheme())) { - // Domian may be specified in a fully qualified user name - return new NTCredentials( - systemcreds.getUserName(), - new String(systemcreds.getPassword()), - null, null); - } else { - return new UsernamePasswordCredentials( - systemcreds.getUserName(), - new String(systemcreds.getPassword())); - } - } - } - } - return null; - } - - public void clear() { - internal.clear(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/TargetAuthenticationStrategy.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/TargetAuthenticationStrategy.java deleted file mode 100644 index dad2eb71..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/TargetAuthenticationStrategy.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.util.Collection; - -import org.apache.http.HttpStatus; -import org.apache.http.annotation.Immutable; -import org.apache.http.auth.AUTH; -import org.apache.http.client.config.RequestConfig; - -/** - * Default {@link org.apache.http.client.AuthenticationStrategy} implementation - * for proxy host authentication. - * - * @since 4.2 - */ -@Immutable -public class TargetAuthenticationStrategy extends AuthenticationStrategyImpl { - - public static final TargetAuthenticationStrategy INSTANCE = new TargetAuthenticationStrategy(); - - public TargetAuthenticationStrategy() { - super(HttpStatus.SC_UNAUTHORIZED, AUTH.WWW_AUTH); - } - - @Override - Collection getPreferredAuthSchemes(final RequestConfig config) { - return config.getTargetPreferredAuthSchemes(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/client/package-info.java deleted file mode 100644 index f31d199c..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/client/package-info.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Default HTTP client implementation. - *

    - * The usual execution flow can be demonstrated by the code snippet below: - *

    - * CloseableHttpClient httpclient = HttpClients.createDefault();
    - * try {
    - *      HttpGetHC4 httpGet = new HttpGetHC4("http://targethost/homepage");
    - *      CloseableHttpResponse response = httpclient.execute(httpGet);
    - *      try {
    - *          System.out.println(response.getStatusLine());
    - *          HttpEntity entity = response.getEntity();
    - *          // do something useful with the response body
    - *          // and ensure it is fully consumed
    - *          EntityUtilsHC4.consume(entity);
    - *      } finally {
    - *          response.close();
    - *      }
    - * } finally {
    - *      httpclient.close();
    - * }
    - * 
    - */ -package org.apache.http.impl.client; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/BasicHttpClientConnectionManager.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/BasicHttpClientConnectionManager.java deleted file mode 100644 index 5fe6bd17..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/BasicHttpClientConnectionManager.java +++ /dev/null @@ -1,374 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.conn; - -import java.io.Closeable; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.Date; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import android.util.Log; - -import org.apache.http.HttpClientConnection; -import org.apache.http.HttpHost; -import org.apache.http.annotation.GuardedBy; -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.config.ConnectionConfig; -import org.apache.http.config.Lookup; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.config.SocketConfig; -import org.apache.http.conn.ConnectionRequest; -import org.apache.http.conn.DnsResolver; -import org.apache.http.conn.HttpClientConnectionManager; -import org.apache.http.conn.HttpConnectionFactory; -import org.apache.http.conn.SchemePortResolver; -import org.apache.http.conn.ManagedHttpClientConnection; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; -import org.apache.http.util.Asserts; -import org.apache.http.util.LangUtils; - -/** - * A connection manager for a single connection. This connection manager maintains only one active - * connection. Even though this class is fully thread-safe it ought to be used by one execution - * thread only, as only one thread a time can lease the connection at a time. - *

    - * This connection manager will make an effort to reuse the connection for subsequent requests - * with the same {@link HttpRoute route}. It will, however, close the existing connection and - * open it for the given route, if the route of the persistent connection does not match that - * of the connection request. If the connection has been already been allocated - * {@link IllegalStateException} is thrown. - *

    - * This connection manager implementation should be used inside an EJB container instead of - * {@link PoolingHttpClientConnectionManager}. - * - * @since 4.3 - */ -@ThreadSafe -public class BasicHttpClientConnectionManager implements HttpClientConnectionManager, Closeable { - - private final static String TAG = "HttpClient"; - - private final HttpClientConnectionOperator connectionOperator; - private final HttpConnectionFactory connFactory; - - @GuardedBy("this") - private ManagedHttpClientConnection conn; - - @GuardedBy("this") - private HttpRoute route; - - @GuardedBy("this") - private Object state; - - @GuardedBy("this") - private long updated; - - @GuardedBy("this") - private long expiry; - - @GuardedBy("this") - private boolean leased; - - @GuardedBy("this") - private SocketConfig socketConfig; - - @GuardedBy("this") - private ConnectionConfig connConfig; - - private final AtomicBoolean isShutdown; - - private static Registry getDefaultRegistry() { - return RegistryBuilder.create() - .register("http", PlainConnectionSocketFactory.getSocketFactory()) - .register("https", SSLConnectionSocketFactory.getSocketFactory()) - .build(); - } - - public BasicHttpClientConnectionManager( - final Lookup socketFactoryRegistry, - final HttpConnectionFactory connFactory, - final SchemePortResolver schemePortResolver, - final DnsResolver dnsResolver) { - super(); - this.connectionOperator = new HttpClientConnectionOperator( - socketFactoryRegistry, schemePortResolver, dnsResolver); - this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE; - this.expiry = Long.MAX_VALUE; - this.socketConfig = SocketConfig.DEFAULT; - this.connConfig = ConnectionConfig.DEFAULT; - this.isShutdown = new AtomicBoolean(false); - } - - public BasicHttpClientConnectionManager( - final Lookup socketFactoryRegistry, - final HttpConnectionFactory connFactory) { - this(socketFactoryRegistry, connFactory, null, null); - } - - public BasicHttpClientConnectionManager( - final Lookup socketFactoryRegistry) { - this(socketFactoryRegistry, null, null, null); - } - - public BasicHttpClientConnectionManager() { - this(getDefaultRegistry(), null, null, null); - } - - @Override - protected void finalize() throws Throwable { - try { - shutdown(); - } finally { // Make sure we call overridden method even if shutdown barfs - super.finalize(); - } - } - - public void close() { - shutdown(); - } - - HttpRoute getRoute() { - return route; - } - - Object getState() { - return state; - } - - public synchronized SocketConfig getSocketConfig() { - return socketConfig; - } - - public synchronized void setSocketConfig(final SocketConfig socketConfig) { - this.socketConfig = socketConfig != null ? socketConfig : SocketConfig.DEFAULT; - } - - public synchronized ConnectionConfig getConnectionConfig() { - return connConfig; - } - - public synchronized void setConnectionConfig(final ConnectionConfig connConfig) { - this.connConfig = connConfig != null ? connConfig : ConnectionConfig.DEFAULT; - } - - public final ConnectionRequest requestConnection( - final HttpRoute route, - final Object state) { - Args.notNull(route, "Route"); - return new ConnectionRequest() { - - public boolean cancel() { - // Nothing to abort, since requests are immediate. - return false; - } - - public HttpClientConnection get(final long timeout, final TimeUnit tunit) { - return BasicHttpClientConnectionManager.this.getConnection( - route, state); - } - - }; - } - - private void closeConnection() { - if (this.conn != null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Closing connection"); - } - try { - this.conn.close(); - } catch (final IOException iox) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "I/O exception closing connection", iox); - } - } - this.conn = null; - } - } - - private void shutdownConnection() { - if (this.conn != null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Shutting down connection"); - } - try { - this.conn.shutdown(); - } catch (final IOException iox) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "I/O exception shutting down connection", iox); - } - } - this.conn = null; - } - } - - private void checkExpiry() { - if (this.conn != null && System.currentTimeMillis() >= this.expiry) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Connection expired @ " + new Date(this.expiry)); - } - closeConnection(); - } - } - - synchronized HttpClientConnection getConnection(final HttpRoute route, final Object state) { - Asserts.check(!this.isShutdown.get(), "Connection manager has been shut down"); - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Get connection for route " + route); - } - Asserts.check(!this.leased, "Connection is still allocated"); - if (!LangUtils.equals(this.route, route) || !LangUtils.equals(this.state, state)) { - closeConnection(); - } - this.route = route; - this.state = state; - checkExpiry(); - if (this.conn == null) { - this.conn = this.connFactory.create(route, this.connConfig); - } - this.leased = true; - return this.conn; - } - - public synchronized void releaseConnection( - final HttpClientConnection conn, - final Object state, - final long keepalive, final TimeUnit tunit) { - Args.notNull(conn, "Connection"); - Asserts.check(conn == this.conn, "Connection not obtained from this manager"); - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Releasing connection " + conn); - } - if (this.isShutdown.get()) { - return; - } - try { - this.updated = System.currentTimeMillis(); - if (!this.conn.isOpen()) { - this.conn = null; - this.route = null; - this.conn = null; - this.expiry = Long.MAX_VALUE; - } else { - this.state = state; - if (Log.isLoggable(TAG, Log.DEBUG)) { - final String s; - if (keepalive > 0) { - s = "for " + keepalive + " " + tunit; - } else { - s = "indefinitely"; - } - Log.d(TAG, "Connection can be kept alive " + s); - } - if (keepalive > 0) { - this.expiry = this.updated + tunit.toMillis(keepalive); - } else { - this.expiry = Long.MAX_VALUE; - } - } - } finally { - this.leased = false; - } - } - - public void connect( - final HttpClientConnection conn, - final HttpRoute route, - final int connectTimeout, - final HttpContext context) throws IOException { - Args.notNull(conn, "Connection"); - Args.notNull(route, "HTTP route"); - Asserts.check(conn == this.conn, "Connection not obtained from this manager"); - final HttpHost host; - if (route.getProxyHost() != null) { - host = route.getProxyHost(); - } else { - host = route.getTargetHost(); - } - final InetSocketAddress localAddress = route.getLocalAddress() != null ? new InetSocketAddress(route.getLocalAddress(), 0) : null;; - this.connectionOperator.connect(this.conn, host, localAddress, - connectTimeout, this.socketConfig, context); - } - - public void upgrade( - final HttpClientConnection conn, - final HttpRoute route, - final HttpContext context) throws IOException { - Args.notNull(conn, "Connection"); - Args.notNull(route, "HTTP route"); - Asserts.check(conn == this.conn, "Connection not obtained from this manager"); - this.connectionOperator.upgrade(this.conn, route.getTargetHost(), context); - } - - public void routeComplete( - final HttpClientConnection conn, - final HttpRoute route, - final HttpContext context) throws IOException { - } - - public synchronized void closeExpiredConnections() { - if (this.isShutdown.get()) { - return; - } - if (!this.leased) { - checkExpiry(); - } - } - - public synchronized void closeIdleConnections(final long idletime, final TimeUnit tunit) { - Args.notNull(tunit, "Time unit"); - if (this.isShutdown.get()) { - return; - } - if (!this.leased) { - long time = tunit.toMillis(idletime); - if (time < 0) { - time = 0; - } - final long deadline = System.currentTimeMillis() - time; - if (this.updated <= deadline) { - closeConnection(); - } - } - } - - public synchronized void shutdown() { - if (this.isShutdown.compareAndSet(false, true)) { - shutdownConnection(); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/CPool.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/CPool.java deleted file mode 100644 index 62ed7e28..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/CPool.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.conn; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -import android.util.Log; - -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.conn.ManagedHttpClientConnection; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.pool.AbstractConnPool; -import org.apache.http.pool.ConnFactory; - -/** - * @since 4.3 - */ -@ThreadSafe -class CPool extends AbstractConnPool { - - private static final AtomicLong COUNTER = new AtomicLong(); - - private final long timeToLive; - private final TimeUnit tunit; - - public CPool( - final ConnFactory connFactory, - final int defaultMaxPerRoute, final int maxTotal, - final long timeToLive, final TimeUnit tunit) { - super(connFactory, defaultMaxPerRoute, maxTotal); - this.timeToLive = timeToLive; - this.tunit = tunit; - } - - @Override - protected CPoolEntry createEntry(final HttpRoute route, final ManagedHttpClientConnection conn) { - final String id = Long.toString(COUNTER.getAndIncrement()); - return new CPoolEntry(id, route, conn, this.timeToLive, this.tunit); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/CPoolEntry.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/CPoolEntry.java deleted file mode 100644 index 5bf3cc23..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/CPoolEntry.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.conn; - -import java.io.IOException; -import java.util.Date; -import java.util.concurrent.TimeUnit; - -import android.util.Log; -import org.apache.http.HttpClientConnection; -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.conn.ManagedHttpClientConnection; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.pool.PoolEntry; - -/** - * @since 4.3 - */ -@ThreadSafe -class CPoolEntry extends PoolEntry { - - private final static String TAG = "HttpClient"; - - private volatile boolean routeComplete; - - public CPoolEntry( - final String id, - final HttpRoute route, - final ManagedHttpClientConnection conn, - final long timeToLive, final TimeUnit tunit) { - super(id, route, conn, timeToLive, tunit); - } - - public void markRouteComplete() { - this.routeComplete = true; - } - - public boolean isRouteComplete() { - return this.routeComplete; - } - - public void closeConnection() throws IOException { - final HttpClientConnection conn = getConnection(); - conn.close(); - } - - public void shutdownConnection() throws IOException { - final HttpClientConnection conn = getConnection(); - conn.shutdown(); - } - - @Override - public boolean isExpired(final long now) { - final boolean expired = super.isExpired(now); - if (expired && Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Connection " + this + " expired @ " + new Date(getExpiry())); - } - return expired; - } - - @Override - public boolean isClosed() { - final HttpClientConnection conn = getConnection(); - return !conn.isOpen(); - } - - @Override - public void close() { - try { - closeConnection(); - } catch (final IOException ex) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "I/O error closing connection", ex); - } - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/CPoolProxy.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/CPoolProxy.java deleted file mode 100644 index a2d4cacb..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/CPoolProxy.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.conn; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.Socket; - -import javax.net.ssl.SSLSession; - -import org.apache.http.HttpClientConnection; -import org.apache.http.HttpConnectionMetrics; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.conn.ManagedHttpClientConnection; -import org.apache.http.protocol.HttpContext; - -/** - * @since 4.3 - */ -@NotThreadSafe -class CPoolProxy implements ManagedHttpClientConnection, HttpContext { - - private volatile CPoolEntry poolEntry; - - CPoolProxy(final CPoolEntry entry) { - super(); - this.poolEntry = entry; - } - - CPoolEntry getPoolEntry() { - return this.poolEntry; - } - - CPoolEntry detach() { - final CPoolEntry local = this.poolEntry; - this.poolEntry = null; - return local; - } - - ManagedHttpClientConnection getConnection() { - final CPoolEntry local = this.poolEntry; - if (local == null) { - return null; - } - return local.getConnection(); - } - - ManagedHttpClientConnection getValidConnection() { - final ManagedHttpClientConnection conn = getConnection(); - if (conn == null) { - throw new ConnectionShutdownException(); - } - return conn; - } - - public void close() throws IOException { - final CPoolEntry local = this.poolEntry; - if (local != null) { - local.closeConnection(); - } - } - - public void shutdown() throws IOException { - final CPoolEntry local = this.poolEntry; - if (local != null) { - local.shutdownConnection(); - } - } - - public boolean isOpen() { - final CPoolEntry local = this.poolEntry; - if (local != null) { - return !local.isClosed(); - } else { - return false; - } - } - - public boolean isStale() { - final HttpClientConnection conn = getConnection(); - if (conn != null) { - return conn.isStale(); - } else { - return true; - } - } - - public void setSocketTimeout(final int timeout) { - getValidConnection().setSocketTimeout(timeout); - } - - public int getSocketTimeout() { - return getValidConnection().getSocketTimeout(); - } - - public String getId() { - return getValidConnection().getId(); - } - - public void bind(final Socket socket) throws IOException { - getValidConnection().bind(socket); - } - - public Socket getSocket() { - return getValidConnection().getSocket(); - } - - public SSLSession getSSLSession() { - return getValidConnection().getSSLSession(); - } - - public boolean isResponseAvailable(final int timeout) throws IOException { - return getValidConnection().isResponseAvailable(timeout); - } - - public void sendRequestHeader(final HttpRequest request) throws HttpException, IOException { - getValidConnection().sendRequestHeader(request); - } - - public void sendRequestEntity(final HttpEntityEnclosingRequest request) throws HttpException, IOException { - getValidConnection().sendRequestEntity(request); - } - - public HttpResponse receiveResponseHeader() throws HttpException, IOException { - return getValidConnection().receiveResponseHeader(); - } - - public void receiveResponseEntity(final HttpResponse response) throws HttpException, IOException { - getValidConnection().receiveResponseEntity(response); - } - - public void flush() throws IOException { - getValidConnection().flush(); - } - - public HttpConnectionMetrics getMetrics() { - return getValidConnection().getMetrics(); - } - - public InetAddress getLocalAddress() { - return getValidConnection().getLocalAddress(); - } - - public int getLocalPort() { - return getValidConnection().getLocalPort(); - } - - public InetAddress getRemoteAddress() { - return getValidConnection().getRemoteAddress(); - } - - public int getRemotePort() { - return getValidConnection().getRemotePort(); - } - - public Object getAttribute(final String id) { - final ManagedHttpClientConnection conn = getValidConnection(); - if (conn instanceof HttpContext) { - return ((HttpContext) conn).getAttribute(id); - } else { - return null; - } - } - - public void setAttribute(final String id, final Object obj) { - final ManagedHttpClientConnection conn = getValidConnection(); - if (conn instanceof HttpContext) { - ((HttpContext) conn).setAttribute(id, obj); - } - } - - public Object removeAttribute(final String id) { - final ManagedHttpClientConnection conn = getValidConnection(); - if (conn instanceof HttpContext) { - return ((HttpContext) conn).removeAttribute(id); - } else { - return null; - } - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("CPoolProxy{"); - final ManagedHttpClientConnection conn = getConnection(); - if (conn != null) { - sb.append(conn); - } else { - sb.append("detached"); - } - sb.append('}'); - return sb.toString(); - } - - public static HttpClientConnection newProxy(final CPoolEntry poolEntry) { - return new CPoolProxy(poolEntry); - } - - private static CPoolProxy getProxy(final HttpClientConnection conn) { - if (!CPoolProxy.class.isInstance(conn)) { - throw new IllegalStateException("Unexpected connection proxy class: " + conn.getClass()); - } - return CPoolProxy.class.cast(conn); - } - - public static CPoolEntry getPoolEntry(final HttpClientConnection proxy) { - final CPoolEntry entry = getProxy(proxy).getPoolEntry(); - if (entry == null) { - throw new ConnectionShutdownException(); - } - return entry; - } - - public static CPoolEntry detach(final HttpClientConnection conn) { - return getProxy(conn).detach(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/ConnectionShutdownException.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/ConnectionShutdownException.java deleted file mode 100644 index 0d674539..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/ConnectionShutdownException.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.conn; - -import org.apache.http.annotation.Immutable; - -/** - * Signals that the connection has been shut down or released back to the - * the connection pool - * - * @since 4.1 - */ -@Immutable -public class ConnectionShutdownException extends IllegalStateException { - - private static final long serialVersionUID = 5868657401162844497L; - - /** - * Creates a new ConnectionShutdownException with a null detail message. - */ - public ConnectionShutdownException() { - super(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultHttpResponseParser.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultHttpResponseParser.java deleted file mode 100644 index e7e2b73f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultHttpResponseParser.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.conn; - -import java.io.IOException; - -import android.util.Log; - -import org.apache.http.HttpException; -import org.apache.http.HttpResponse; -import org.apache.http.HttpResponseFactory; -import org.apache.http.NoHttpResponseException; -import org.apache.http.ProtocolException; -import org.apache.http.StatusLine; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.config.MessageConstraints; -import org.apache.http.impl.DefaultHttpResponseFactoryHC4; -import org.apache.http.impl.io.AbstractMessageParserHC4; -import org.apache.http.io.SessionInputBuffer; -import org.apache.http.message.LineParser; -import org.apache.http.message.ParserCursor; -import org.apache.http.params.HttpParams; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * Lenient HTTP response parser implementation that can skip malformed data until - * a valid HTTP response message head is encountered. - * - * @since 4.2 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe -public class DefaultHttpResponseParser extends AbstractMessageParserHC4 { - - private final static String TAG = "HttpClient"; - - private final HttpResponseFactory responseFactory; - private final CharArrayBuffer lineBuf; - - /** - * @deprecated (4.3) use {@link DefaultHttpResponseParser#DefaultHttpResponseParser( - * SessionInputBuffer, LineParser, HttpResponseFactory, MessageConstraints)} - */ - @Deprecated - public DefaultHttpResponseParser( - final SessionInputBuffer buffer, - final LineParser parser, - final HttpResponseFactory responseFactory, - final HttpParams params) { - super(buffer, parser, params); - Args.notNull(responseFactory, "Response factory"); - this.responseFactory = responseFactory; - this.lineBuf = new CharArrayBuffer(128); - } - - /** - * Creates new instance of DefaultHttpResponseParser. - * - * @param buffer the session input buffer. - * @param lineParser the line parser. If null - * {@link org.apache.http.message.BasicLineParserHC4#INSTANCE} will be used. - * @param responseFactory HTTP response factory. If null - * {@link DefaultHttpResponseFactoryHC4#INSTANCE} will be used. - * @param constraints the message constraints. If null - * {@link MessageConstraints#DEFAULT} will be used. - * - * @since 4.3 - */ - public DefaultHttpResponseParser( - final SessionInputBuffer buffer, - final LineParser lineParser, - final HttpResponseFactory responseFactory, - final MessageConstraints constraints) { - super(buffer, lineParser, constraints); - this.responseFactory = responseFactory != null ? responseFactory : - DefaultHttpResponseFactoryHC4.INSTANCE; - this.lineBuf = new CharArrayBuffer(128); - } - - /** - * Creates new instance of DefaultHttpResponseParser. - * - * @param buffer the session input buffer. - * @param constraints the message constraints. If null - * {@link MessageConstraints#DEFAULT} will be used. - * - * @since 4.3 - */ - public DefaultHttpResponseParser( - final SessionInputBuffer buffer, final MessageConstraints constraints) { - this(buffer, null, null, constraints); - } - - /** - * Creates new instance of DefaultHttpResponseParser. - * - * @param buffer the session input buffer. - * - * @since 4.3 - */ - public DefaultHttpResponseParser(final SessionInputBuffer buffer) { - this(buffer, null, null, MessageConstraints.DEFAULT); - } - - @Override - protected HttpResponse parseHead( - final SessionInputBuffer sessionBuffer) throws IOException, HttpException { - //read out the HTTP status string - int count = 0; - ParserCursor cursor = null; - do { - // clear the buffer - this.lineBuf.clear(); - final int i = sessionBuffer.readLine(this.lineBuf); - if (i == -1 && count == 0) { - // The server just dropped connection on us - throw new NoHttpResponseException("The target server failed to respond"); - } - cursor = new ParserCursor(0, this.lineBuf.length()); - if (lineParser.hasProtocolVersion(this.lineBuf, cursor)) { - // Got one - break; - } else if (i == -1 || reject(this.lineBuf, count)) { - // Giving up - throw new ProtocolException("The server failed to respond with a " + - "valid HTTP response"); - } - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Garbage in response: " + this.lineBuf.toString()); - } - count++; - } while(true); - //create the status line from the status string - final StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, cursor); - return this.responseFactory.newHttpResponse(statusline, null); - } - - protected boolean reject(final CharArrayBuffer line, final int count) { - return false; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultHttpResponseParserFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultHttpResponseParserFactory.java deleted file mode 100644 index 7db11353..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultHttpResponseParserFactory.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.conn; - -import org.apache.http.HttpResponse; -import org.apache.http.HttpResponseFactory; -import org.apache.http.annotation.Immutable; -import org.apache.http.config.MessageConstraints; -import org.apache.http.impl.DefaultHttpResponseFactoryHC4; -import org.apache.http.io.HttpMessageParser; -import org.apache.http.io.HttpMessageParserFactory; -import org.apache.http.io.SessionInputBuffer; -import org.apache.http.message.BasicLineParserHC4; -import org.apache.http.message.LineParser; - -/** - * Default factory for response message parsers. - * - * @since 4.3 - */ -@Immutable -public class DefaultHttpResponseParserFactory implements HttpMessageParserFactory { - - public static final DefaultHttpResponseParserFactory INSTANCE = new DefaultHttpResponseParserFactory(); - - private final LineParser lineParser; - private final HttpResponseFactory responseFactory; - - public DefaultHttpResponseParserFactory( - final LineParser lineParser, - final HttpResponseFactory responseFactory) { - super(); - this.lineParser = lineParser != null ? lineParser : BasicLineParserHC4.INSTANCE; - this.responseFactory = responseFactory != null ? responseFactory - : DefaultHttpResponseFactoryHC4.INSTANCE; - } - - public DefaultHttpResponseParserFactory( - final HttpResponseFactory responseFactory) { - this(null, responseFactory); - } - - public DefaultHttpResponseParserFactory() { - this(null, null); - } - - public HttpMessageParser create(final SessionInputBuffer buffer, - final MessageConstraints constraints) { - return new DefaultHttpResponseParser(buffer, lineParser, responseFactory, constraints); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultManagedHttpClientConnection.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultManagedHttpClientConnection.java deleted file mode 100644 index 18d1d120..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultManagedHttpClientConnection.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.conn; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.Socket; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; - -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.config.MessageConstraints; -import org.apache.http.conn.ManagedHttpClientConnection; -import org.apache.http.entity.ContentLengthStrategy; -import org.apache.http.impl.DefaultBHttpClientConnection; -import org.apache.http.io.HttpMessageParserFactory; -import org.apache.http.io.HttpMessageWriterFactory; -import org.apache.http.protocol.HttpContext; - -/** - * Default {@link ManagedHttpClientConnection} implementation. - * @since 4.3 - */ -@NotThreadSafe -public class DefaultManagedHttpClientConnection extends DefaultBHttpClientConnection - implements ManagedHttpClientConnection, HttpContext { - - private final String id; - private final Map attributes; - - private volatile boolean shutdown; - - public DefaultManagedHttpClientConnection( - final String id, - final int buffersize, - final int fragmentSizeHint, - final CharsetDecoder chardecoder, - final CharsetEncoder charencoder, - final MessageConstraints constraints, - final ContentLengthStrategy incomingContentStrategy, - final ContentLengthStrategy outgoingContentStrategy, - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory) { - super(buffersize, fragmentSizeHint, chardecoder, charencoder, - constraints, incomingContentStrategy, outgoingContentStrategy, - requestWriterFactory, responseParserFactory); - this.id = id; - this.attributes = new ConcurrentHashMap(); - } - - public DefaultManagedHttpClientConnection( - final String id, - final int buffersize) { - this(id, buffersize, buffersize, null, null, null, null, null, null, null); - } - - public String getId() { - return this.id; - } - - @Override - public void shutdown() throws IOException { - this.shutdown = true; - super.shutdown(); - } - - public Object getAttribute(final String id) { - return this.attributes.get(id); - } - - public Object removeAttribute(final String id) { - return this.attributes.remove(id); - } - - public void setAttribute(final String id, final Object obj) { - this.attributes.put(id, obj); - } - - @Override - public void bind(final Socket socket) throws IOException { - if (this.shutdown) { - socket.close(); // allow this to throw... - // ...but if it doesn't, explicitly throw one ourselves. - throw new InterruptedIOException("Connection already shutdown"); - } - super.bind(socket); - } - - @Override - public Socket getSocket() { - return super.getSocket(); - } - - public SSLSession getSSLSession() { - final Socket socket = super.getSocket(); - if (socket instanceof SSLSocket) { - return ((SSLSocket) socket).getSession(); - } else { - return null; - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultProxyRoutePlanner.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultProxyRoutePlanner.java deleted file mode 100644 index 376654a0..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultProxyRoutePlanner.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.conn; - -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.annotation.Immutable; -import org.apache.http.conn.SchemePortResolver; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; - -/** - * Implementation of an {@link org.apache.http.conn.routing.HttpRoutePlanner} - * that routes requests through a default proxy. - * - * @since 4.3 - */ -@Immutable -public class DefaultProxyRoutePlanner extends DefaultRoutePlanner { - - private final HttpHost proxy; - - public DefaultProxyRoutePlanner(final HttpHost proxy, final SchemePortResolver schemePortResolver) { - super(schemePortResolver); - this.proxy = Args.notNull(proxy, "Proxy host"); - } - - public DefaultProxyRoutePlanner(final HttpHost proxy) { - this(proxy, null); - } - - @Override - protected HttpHost determineProxy( - final HttpHost target, - final HttpRequest request, - final HttpContext context) throws HttpException { - return proxy; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultRoutePlanner.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultRoutePlanner.java deleted file mode 100644 index 2b21f1a3..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultRoutePlanner.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.conn; - -import java.net.InetAddress; - -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.ProtocolException; -import org.apache.http.annotation.Immutable; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.conn.SchemePortResolver; -import org.apache.http.conn.UnsupportedSchemeException; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.conn.routing.HttpRoutePlanner; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; - -/** - * Default implementation of an {@link HttpRoutePlanner}. It will not make use of - * any Java system properties, nor of system or browser proxy settings. - * - * @since 4.3 - */ -@Immutable -public class DefaultRoutePlanner implements HttpRoutePlanner { - - private final SchemePortResolver schemePortResolver; - - public DefaultRoutePlanner(final SchemePortResolver schemePortResolver) { - super(); - this.schemePortResolver = schemePortResolver != null ? schemePortResolver : - DefaultSchemePortResolver.INSTANCE; - } - - public HttpRoute determineRoute( - final HttpHost host, - final HttpRequest request, - final HttpContext context) throws HttpException { - Args.notNull(request, "Request"); - if (host == null) { - throw new ProtocolException("Target host is not specified"); - } - final HttpClientContext clientContext = HttpClientContext.adapt(context); - final RequestConfig config = clientContext.getRequestConfig(); - final InetAddress local = config.getLocalAddress(); - HttpHost proxy = config.getProxy(); - if (proxy == null) { - proxy = determineProxy(host, request, context); - } - - final HttpHost target; - if (host.getPort() <= 0) { - try { - target = new HttpHost( - host.getHostName(), - this.schemePortResolver.resolve(host), - host.getSchemeName()); - } catch (final UnsupportedSchemeException ex) { - throw new HttpException(ex.getMessage()); - } - } else { - target = host; - } - final boolean secure = target.getSchemeName().equalsIgnoreCase("https"); - if (proxy == null) { - return new HttpRoute(target, local, secure); - } else { - return new HttpRoute(target, local, proxy, secure); - } - } - - protected HttpHost determineProxy( - final HttpHost target, - final HttpRequest request, - final HttpContext context) throws HttpException { - return null; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultSchemePortResolver.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultSchemePortResolver.java deleted file mode 100644 index c8abe8e7..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/DefaultSchemePortResolver.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.conn; - -import org.apache.http.HttpHost; -import org.apache.http.annotation.Immutable; -import org.apache.http.conn.SchemePortResolver; -import org.apache.http.conn.UnsupportedSchemeException; -import org.apache.http.util.Args; - -/** - * Default {@link SchemePortResolver}. - * - * @since 4.3 - */ -@Immutable -public class DefaultSchemePortResolver implements SchemePortResolver { - - public static final DefaultSchemePortResolver INSTANCE = new DefaultSchemePortResolver(); - - public int resolve(final HttpHost host) throws UnsupportedSchemeException { - Args.notNull(host, "HTTP host"); - final int port = host.getPort(); - if (port > 0) { - return port; - } - final String name = host.getSchemeName(); - if (name.equalsIgnoreCase("http")) { - return 80; - } else if (name.equalsIgnoreCase("https")) { - return 443; - } else { - throw new UnsupportedSchemeException(name + " protocol is not supported"); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/HttpClientConnectionOperator.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/HttpClientConnectionOperator.java deleted file mode 100644 index 84be24cf..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/HttpClientConnectionOperator.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.conn; - -import java.io.IOException; -import java.net.ConnectException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.SocketTimeoutException; -import java.util.Arrays; - -import android.util.Log; - -import org.apache.http.HttpHost; -import org.apache.http.annotation.Immutable; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.config.Lookup; -import org.apache.http.config.SocketConfig; -import org.apache.http.conn.ConnectTimeoutException; -import org.apache.http.conn.DnsResolver; -import org.apache.http.conn.HttpHostConnectException; -import org.apache.http.conn.ManagedHttpClientConnection; -import org.apache.http.conn.SchemePortResolver; -import org.apache.http.conn.UnsupportedSchemeException; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.LayeredConnectionSocketFactory; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; - -@Immutable -class HttpClientConnectionOperator { - - static final String SOCKET_FACTORY_REGISTRY = "http.socket-factory-registry"; - - private final static String TAG = "HttpClient"; - - private final Lookup socketFactoryRegistry; - private final SchemePortResolver schemePortResolver; - private final DnsResolver dnsResolver; - - HttpClientConnectionOperator( - final Lookup socketFactoryRegistry, - final SchemePortResolver schemePortResolver, - final DnsResolver dnsResolver) { - super(); - Args.notNull(socketFactoryRegistry, "Socket factory registry"); - this.socketFactoryRegistry = socketFactoryRegistry; - this.schemePortResolver = schemePortResolver != null ? schemePortResolver : - DefaultSchemePortResolver.INSTANCE; - this.dnsResolver = dnsResolver != null ? dnsResolver : - SystemDefaultDnsResolver.INSTANCE; - } - - @SuppressWarnings("unchecked") - private Lookup getSocketFactoryRegistry(final HttpContext context) { - Lookup reg = (Lookup) context.getAttribute( - SOCKET_FACTORY_REGISTRY); - if (reg == null) { - reg = this.socketFactoryRegistry; - } - return reg; - } - - public void connect( - final ManagedHttpClientConnection conn, - final HttpHost host, - final InetSocketAddress localAddress, - final int connectTimeout, - final SocketConfig socketConfig, - final HttpContext context) throws IOException { - final Lookup registry = getSocketFactoryRegistry(context); - final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName()); - if (sf == null) { - throw new UnsupportedSchemeException(host.getSchemeName() + - " protocol is not supported"); - } - final InetAddress[] addresses = this.dnsResolver.resolve(host.getHostName()); - final int port = this.schemePortResolver.resolve(host); - for (int i = 0; i < addresses.length; i++) { - final InetAddress address = addresses[i]; - final boolean last = i == addresses.length - 1; - - Socket sock = sf.createSocket(context); - sock.setSoTimeout(socketConfig.getSoTimeout()); - sock.setReuseAddress(socketConfig.isSoReuseAddress()); - sock.setTcpNoDelay(socketConfig.isTcpNoDelay()); - sock.setKeepAlive(socketConfig.isSoKeepAlive()); - final int linger = socketConfig.getSoLinger(); - if (linger >= 0) { - sock.setSoLinger(linger > 0, linger); - } - conn.bind(sock); - - final InetSocketAddress remoteAddress = new InetSocketAddress(address, port); - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Connecting to " + remoteAddress); - } - try { - sock = sf.connectSocket( - connectTimeout, sock, host, remoteAddress, localAddress, context); - conn.bind(sock); - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Connection established " + conn); - } - return; - } catch (final SocketTimeoutException ex) { - if (last) { - final ConnectTimeoutException cex = new ConnectTimeoutException( - getConnectTimeoutMessage(ex, host, addresses)); - cex.initCause(ex); - } - } catch (final ConnectException ex) { - if (last) { - final String msg = ex.getMessage(); - if ("Connection timed out".equals(msg)) { - final ConnectTimeoutException cex = new ConnectTimeoutException( - getConnectTimeoutMessage(ex, host, addresses)); - cex.initCause(ex); - throw cex; - } else { - throw new HttpHostConnectException(host, ex); - } - } - } - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Connect to " + remoteAddress + " timed out. " + - "Connection will be retried using another IP address"); - } - } - } - - private static String getConnectTimeoutMessage( - final IOException cause, - final HttpHost host, - final InetAddress... remoteAddresses) { - return "Connect to " + - (host != null ? host.toHostString() : "remote host") + - (remoteAddresses != null && remoteAddresses .length > 0 ? - " " + Arrays.asList(remoteAddresses) : "") + - ((cause != null && cause.getMessage() != null) ? - " failed: " + cause.getMessage() : " timed out"); - } - - public void upgrade( - final ManagedHttpClientConnection conn, - final HttpHost host, - final HttpContext context) throws IOException { - final HttpClientContext clientContext = HttpClientContext.adapt(context); - final Lookup registry = getSocketFactoryRegistry(clientContext); - final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName()); - if (sf == null) { - throw new UnsupportedSchemeException(host.getSchemeName() + - " protocol is not supported"); - } - if (!(sf instanceof LayeredConnectionSocketFactory)) { - throw new UnsupportedSchemeException(host.getSchemeName() + - " protocol does not support connection upgrade"); - } - final LayeredConnectionSocketFactory lsf = (LayeredConnectionSocketFactory) sf; - Socket sock = conn.getSocket(); - final int port = this.schemePortResolver.resolve(host); - sock = lsf.createLayeredSocket(sock, host.getHostName(), port, context); - conn.bind(sock); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/InMemoryDnsResolver.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/InMemoryDnsResolver.java deleted file mode 100644 index 3e73e964..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/InMemoryDnsResolver.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.conn; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Arrays; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import android.util.Log; - -import org.apache.http.conn.DnsResolver; -import org.apache.http.util.Args; - -/** - * In-memory {@link DnsResolver} implementation. - * - * @since 4.2 - */ -public class InMemoryDnsResolver implements DnsResolver { - - /** Logger associated to this class. */ - private final static String TAG = "HttpClient"; - - /** - * In-memory collection that will hold the associations between a host name - * and an array of InetAddress instances. - */ - private final Map dnsMap; - - /** - * Builds a DNS resolver that will resolve the host names against a - * collection held in-memory. - */ - public InMemoryDnsResolver() { - dnsMap = new ConcurrentHashMap(); - } - - /** - * Associates the given array of IP addresses to the given host in this DNS overrider. - * The IP addresses are assumed to be already resolved. - * - * @param host - * The host name to be associated with the given IP. - * @param ips - * array of IP addresses to be resolved by this DNS overrider to the given - * host name. - */ - public void add(final String host, final InetAddress... ips) { - Args.notNull(host, "Host name"); - Args.notNull(ips, "Array of IP addresses"); - dnsMap.put(host, ips); - } - - /** - * {@inheritDoc} - */ - public InetAddress[] resolve(final String host) throws UnknownHostException { - final InetAddress[] resolvedAddresses = dnsMap.get(host); - if (Log.isLoggable(TAG, Log.INFO)) { - Log.i(TAG, "Resolving " + host + " to " + Arrays.deepToString(resolvedAddresses)); - } - if(resolvedAddresses == null){ - throw new UnknownHostException(host + " cannot be resolved"); - } - return resolvedAddresses; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/LoggingInputStream.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/LoggingInputStream.java deleted file mode 100644 index 4d3a02fd..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/LoggingInputStream.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.conn; - -import org.apache.http.annotation.NotThreadSafe; - -import java.io.IOException; -import java.io.InputStream; - -/** - * Internal class. - * - * @since 4.3 - */ -@NotThreadSafe -class LoggingInputStream extends InputStream { - - private final InputStream in; - private final WireHC4 wire; - - public LoggingInputStream(final InputStream in, final WireHC4 wire) { - super(); - this.in = in; - this.wire = wire; - } - - @Override - public int read() throws IOException { - try { - final int b = in.read(); - if (b == -1) { - wire.input("end of stream"); - } else { - wire.input(b); - } - return b; - } catch (IOException ex) { - wire.input("[read] I/O error: " + ex.getMessage()); - throw ex; - } - } - - @Override - public int read(final byte[] b) throws IOException { - try { - final int bytesRead = in.read(b); - if (bytesRead == -1) { - wire.input("end of stream"); - } else if (bytesRead > 0) { - wire.input(b, 0, bytesRead); - } - return bytesRead; - } catch (IOException ex) { - wire.input("[read] I/O error: " + ex.getMessage()); - throw ex; - } - } - - @Override - public int read(final byte[] b, final int off, final int len) throws IOException { - try { - final int bytesRead = in.read(b, off, len); - if (bytesRead == -1) { - wire.input("end of stream"); - } else if (bytesRead > 0) { - wire.input(b, off, bytesRead); - } - return bytesRead; - } catch (IOException ex) { - wire.input("[read] I/O error: " + ex.getMessage()); - throw ex; - } - } - - @Override - public long skip(final long n) throws IOException { - try { - return super.skip(n); - } catch (IOException ex) { - wire.input("[skip] I/O error: " + ex.getMessage()); - throw ex; - } - } - - @Override - public int available() throws IOException { - try { - return in.available(); - } catch (IOException ex) { - wire.input("[available] I/O error : " + ex.getMessage()); - throw ex; - } - } - - @Override - public void mark(final int readlimit) { - super.mark(readlimit); - } - - @Override - public void reset() throws IOException { - super.reset(); - } - - @Override - public boolean markSupported() { - return false; - } - - @Override - public void close() throws IOException { - try { - in.close(); - } catch (IOException ex) { - wire.input("[close] I/O error: " + ex.getMessage()); - throw ex; - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/LoggingManagedHttpClientConnection.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/LoggingManagedHttpClientConnection.java deleted file mode 100644 index 15ffe5fb..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/LoggingManagedHttpClientConnection.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.conn; - -import android.util.Log; -import org.apache.http.Header; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.config.MessageConstraints; -import org.apache.http.entity.ContentLengthStrategy; -import org.apache.http.io.HttpMessageParserFactory; -import org.apache.http.io.HttpMessageWriterFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.Socket; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; - -@NotThreadSafe -class LoggingManagedHttpClientConnection extends DefaultManagedHttpClientConnection { - - private final static String TAG = "HttpClient"; - private final static String HEADER_TAG = "Headers"; - private final WireHC4 wire; - - public LoggingManagedHttpClientConnection( - final String id, - final int buffersize, - final int fragmentSizeHint, - final CharsetDecoder chardecoder, - final CharsetEncoder charencoder, - final MessageConstraints constraints, - final ContentLengthStrategy incomingContentStrategy, - final ContentLengthStrategy outgoingContentStrategy, - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory) { - super(id, buffersize, fragmentSizeHint, chardecoder, charencoder, - constraints, incomingContentStrategy, outgoingContentStrategy, - requestWriterFactory, responseParserFactory); - this.wire = new WireHC4(id); - } - - @Override - public void close() throws IOException { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, getId() + ": Close connection"); - } - super.close(); - } - - @Override - public void shutdown() throws IOException { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, getId() + ": Shutdown connection"); - } - super.shutdown(); - } - - @Override - protected InputStream getSocketInputStream(final Socket socket) throws IOException { - InputStream in = super.getSocketInputStream(socket); - if (this.wire.enabled()) { - in = new LoggingInputStream(in, this.wire); - } - return in; - } - - @Override - protected OutputStream getSocketOutputStream(final Socket socket) throws IOException { - OutputStream out = super.getSocketOutputStream(socket); - if (this.wire.enabled()) { - out = new LoggingOutputStream(out, this.wire); - } - return out; - } - - @Override - protected void onResponseReceived(final HttpResponse response) { - if (response != null && Log.isLoggable(HEADER_TAG, Log.DEBUG)) { - Log.d(HEADER_TAG, getId() + " << " + response.getStatusLine().toString()); - final Header[] headers = response.getAllHeaders(); - for (final Header header : headers) { - Log.d(HEADER_TAG, getId() + " << " + header.toString()); - } - } - } - - @Override - protected void onRequestSubmitted(final HttpRequest request) { - if (request != null && Log.isLoggable(HEADER_TAG, Log.DEBUG)) { - Log.d(HEADER_TAG, getId() + " >> " + request.getRequestLine().toString()); - final Header[] headers = request.getAllHeaders(); - for (final Header header : headers) { - Log.d(HEADER_TAG, getId() + " >> " + header.toString()); - } - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/LoggingOutputStream.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/LoggingOutputStream.java deleted file mode 100644 index af41ff1d..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/LoggingOutputStream.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.conn; - -import org.apache.http.annotation.NotThreadSafe; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Internal class. - * - * @since 4.3 - */ -@NotThreadSafe -class LoggingOutputStream extends OutputStream { - - private final OutputStream out; - private final WireHC4 wire; - - public LoggingOutputStream(final OutputStream out, final WireHC4 wire) { - super(); - this.out = out; - this.wire = wire; - } - - @Override - public void write(final int b) throws IOException { - try { - wire.output(b); - } catch (IOException ex) { - wire.output("[write] I/O error: " + ex.getMessage()); - throw ex; - } - } - - @Override - public void write(final byte[] b) throws IOException { - try { - wire.output(b); - out.write(b); - } catch (IOException ex) { - wire.output("[write] I/O error: " + ex.getMessage()); - throw ex; - } - } - - @Override - public void write(final byte[] b, final int off, final int len) throws IOException { - try { - wire.output(b, off, len); - out.write(b, off, len); - } catch (IOException ex) { - wire.output("[write] I/O error: " + ex.getMessage()); - throw ex; - } - } - - @Override - public void flush() throws IOException { - try { - out.flush(); - } catch (IOException ex) { - wire.output("[flush] I/O error: " + ex.getMessage()); - throw ex; - } - } - - @Override - public void close() throws IOException { - try { - out.close(); - } catch (IOException ex) { - wire.output("[close] I/O error: " + ex.getMessage()); - throw ex; - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/ManagedHttpClientConnectionFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/ManagedHttpClientConnectionFactory.java deleted file mode 100644 index 140c2009..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/ManagedHttpClientConnectionFactory.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.conn; - -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CodingErrorAction; -import java.util.concurrent.atomic.AtomicLong; - -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.Immutable; -import org.apache.http.config.ConnectionConfig; -import org.apache.http.conn.HttpConnectionFactory; -import org.apache.http.conn.ManagedHttpClientConnection; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.impl.io.DefaultHttpRequestWriterFactory; -import org.apache.http.io.HttpMessageParserFactory; -import org.apache.http.io.HttpMessageWriterFactory; - -/** - * Factory for {@link ManagedHttpClientConnection} instances. - * @since 4.3 - */ -@Immutable -public class ManagedHttpClientConnectionFactory - implements HttpConnectionFactory { - - private static final AtomicLong COUNTER = new AtomicLong(); - - public static final ManagedHttpClientConnectionFactory INSTANCE = new ManagedHttpClientConnectionFactory(); - - private final HttpMessageWriterFactory requestWriterFactory; - private final HttpMessageParserFactory responseParserFactory; - - public ManagedHttpClientConnectionFactory( - final HttpMessageWriterFactory requestWriterFactory, - final HttpMessageParserFactory responseParserFactory) { - super(); - this.requestWriterFactory = requestWriterFactory != null ? requestWriterFactory : - DefaultHttpRequestWriterFactory.INSTANCE; - this.responseParserFactory = responseParserFactory != null ? responseParserFactory : - DefaultHttpResponseParserFactory.INSTANCE; - } - - public ManagedHttpClientConnectionFactory( - final HttpMessageParserFactory responseParserFactory) { - this(null, responseParserFactory); - } - - public ManagedHttpClientConnectionFactory() { - this(null, null); - } - - public ManagedHttpClientConnection create(final HttpRoute route, final ConnectionConfig config) { - final ConnectionConfig cconfig = config != null ? config : ConnectionConfig.DEFAULT; - CharsetDecoder chardecoder = null; - CharsetEncoder charencoder = null; - final Charset charset = cconfig.getCharset(); - final CodingErrorAction malformedInputAction = cconfig.getMalformedInputAction() != null ? - cconfig.getMalformedInputAction() : CodingErrorAction.REPORT; - final CodingErrorAction unmappableInputAction = cconfig.getUnmappableInputAction() != null ? - cconfig.getUnmappableInputAction() : CodingErrorAction.REPORT; - if (charset != null) { - chardecoder = charset.newDecoder(); - chardecoder.onMalformedInput(malformedInputAction); - chardecoder.onUnmappableCharacter(unmappableInputAction); - charencoder = charset.newEncoder(); - charencoder.onMalformedInput(malformedInputAction); - charencoder.onUnmappableCharacter(unmappableInputAction); - } - final String id = "http-outgoing-" + Long.toString(COUNTER.getAndIncrement()); - return new LoggingManagedHttpClientConnection( - id, - cconfig.getBufferSize(), - cconfig.getFragmentSizeHint(), - chardecoder, - charencoder, - cconfig.getMessageConstraints(), - null, - null, - requestWriterFactory, - responseParserFactory); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/PoolingHttpClientConnectionManager.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/PoolingHttpClientConnectionManager.java deleted file mode 100644 index 551c9263..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/PoolingHttpClientConnectionManager.java +++ /dev/null @@ -1,522 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.conn; - -import java.io.Closeable; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicBoolean; - -import android.util.Log; - -import org.apache.http.HttpClientConnection; -import org.apache.http.HttpHost; -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.config.ConnectionConfig; -import org.apache.http.config.Lookup; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.config.SocketConfig; -import org.apache.http.conn.ConnectionPoolTimeoutException; -import org.apache.http.conn.ConnectionRequest; -import org.apache.http.conn.DnsResolver; -import org.apache.http.conn.HttpClientConnectionManager; -import org.apache.http.conn.HttpConnectionFactory; -import org.apache.http.conn.SchemePortResolver; -import org.apache.http.conn.ManagedHttpClientConnection; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.pool.ConnFactory; -import org.apache.http.pool.ConnPoolControl; -import org.apache.http.pool.PoolStats; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.Args; -import org.apache.http.util.Asserts; - -/** - * ClientConnectionPoolManager maintains a pool of - * {@link HttpClientConnection}s and is able to service connection requests - * from multiple execution threads. Connections are pooled on a per route - * basis. A request for a route which already the manager has persistent - * connections for available in the pool will be services by leasing - * a connection from the pool rather than creating a brand new connection. - *

    - * ClientConnectionPoolManager maintains a maximum limit of connection - * on a per route basis and in total. Per default this implementation will - * create no more than than 2 concurrent connections per given route - * and no more 20 connections in total. For many real-world applications - * these limits may prove too constraining, especially if they use HTTP - * as a transport protocol for their services. Connection limits, however, - * can be adjusted using {@link ConnPoolControl} methods. - * - * @since 4.3 - */ -@ThreadSafe -public class PoolingHttpClientConnectionManager - implements HttpClientConnectionManager, ConnPoolControl, Closeable { - - private final static String TAG = "HttpClient"; - - private final ConfigData configData; - private final CPool pool; - private final HttpClientConnectionOperator connectionOperator; - private final AtomicBoolean isShutDown; - - private static Registry getDefaultRegistry() { - return RegistryBuilder.create() - .register("http", PlainConnectionSocketFactory.getSocketFactory()) - .register("https", SSLConnectionSocketFactory.getSocketFactory()) - .build(); - } - - public PoolingHttpClientConnectionManager() { - this(getDefaultRegistry()); - } - - public PoolingHttpClientConnectionManager(final long timeToLive, final TimeUnit tunit) { - this(getDefaultRegistry(), null, null ,null, timeToLive, tunit); - } - - public PoolingHttpClientConnectionManager( - final Registry socketFactoryRegistry) { - this(socketFactoryRegistry, null, null); - } - - public PoolingHttpClientConnectionManager( - final Registry socketFactoryRegistry, - final DnsResolver dnsResolver) { - this(socketFactoryRegistry, null, dnsResolver); - } - - public PoolingHttpClientConnectionManager( - final Registry socketFactoryRegistry, - final HttpConnectionFactory connFactory) { - this(socketFactoryRegistry, connFactory, null); - } - - public PoolingHttpClientConnectionManager( - final HttpConnectionFactory connFactory) { - this(getDefaultRegistry(), connFactory, null); - } - - public PoolingHttpClientConnectionManager( - final Registry socketFactoryRegistry, - final HttpConnectionFactory connFactory, - final DnsResolver dnsResolver) { - this(socketFactoryRegistry, connFactory, null, dnsResolver, -1, TimeUnit.MILLISECONDS); - } - - public PoolingHttpClientConnectionManager( - final Registry socketFactoryRegistry, - final HttpConnectionFactory connFactory, - final SchemePortResolver schemePortResolver, - final DnsResolver dnsResolver, - final long timeToLive, final TimeUnit tunit) { - super(); - this.configData = new ConfigData(); - this.pool = new CPool( - new InternalConnectionFactory(this.configData, connFactory), 2, 20, timeToLive, tunit); - this.connectionOperator = new HttpClientConnectionOperator( - socketFactoryRegistry, schemePortResolver, dnsResolver); - this.isShutDown = new AtomicBoolean(false); - } - - PoolingHttpClientConnectionManager( - final CPool pool, - final Lookup socketFactoryRegistry, - final SchemePortResolver schemePortResolver, - final DnsResolver dnsResolver) { - super(); - this.configData = new ConfigData(); - this.pool = pool; - this.connectionOperator = new HttpClientConnectionOperator( - socketFactoryRegistry, schemePortResolver, dnsResolver); - this.isShutDown = new AtomicBoolean(false); - } - - @Override - protected void finalize() throws Throwable { - try { - shutdown(); - } finally { - super.finalize(); - } - } - - public void close() { - shutdown(); - } - - private String format(final HttpRoute route, final Object state) { - final StringBuilder buf = new StringBuilder(); - buf.append("[route: ").append(route).append("]"); - if (state != null) { - buf.append("[state: ").append(state).append("]"); - } - return buf.toString(); - } - - private String formatStats(final HttpRoute route) { - final StringBuilder buf = new StringBuilder(); - final PoolStats totals = this.pool.getTotalStats(); - final PoolStats stats = this.pool.getStats(route); - buf.append("[total kept alive: ").append(totals.getAvailable()).append("; "); - buf.append("route allocated: ").append(stats.getLeased() + stats.getAvailable()); - buf.append(" of ").append(stats.getMax()).append("; "); - buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable()); - buf.append(" of ").append(totals.getMax()).append("]"); - return buf.toString(); - } - - private String format(final CPoolEntry entry) { - final StringBuilder buf = new StringBuilder(); - buf.append("[id: ").append(entry.getId()).append("]"); - buf.append("[route: ").append(entry.getRoute()).append("]"); - final Object state = entry.getState(); - if (state != null) { - buf.append("[state: ").append(state).append("]"); - } - return buf.toString(); - } - - public ConnectionRequest requestConnection( - final HttpRoute route, - final Object state) { - Args.notNull(route, "HTTP route"); - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Connection request: " + format(route, state) + formatStats(route)); - } - final Future future = this.pool.lease(route, state, null); - return new ConnectionRequest() { - - public boolean cancel() { - return future.cancel(true); - } - - public HttpClientConnection get( - final long timeout, - final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException { - return leaseConnection(future, timeout, tunit); - } - - }; - - } - - protected HttpClientConnection leaseConnection( - final Future future, - final long timeout, - final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException { - final CPoolEntry entry; - try { - entry = future.get(timeout, tunit); - if (entry == null || future.isCancelled()) { - throw new InterruptedException(); - } - Asserts.check(entry.getConnection() != null, "Pool entry with no connection"); - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Connection leased: " + format(entry) + formatStats(entry.getRoute())); - } - return CPoolProxy.newProxy(entry); - } catch (final TimeoutException ex) { - throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool"); - } - } - - public void releaseConnection( - final HttpClientConnection managedConn, - final Object state, - final long keepalive, final TimeUnit tunit) { - Args.notNull(managedConn, "Managed connection"); - synchronized (managedConn) { - final CPoolEntry entry = CPoolProxy.detach(managedConn); - if (entry == null) { - return; - } - final ManagedHttpClientConnection conn = entry.getConnection(); - try { - if (conn.isOpen()) { - entry.setState(state); - entry.updateExpiry(keepalive, tunit != null ? tunit : TimeUnit.MILLISECONDS); - if (Log.isLoggable(TAG, Log.DEBUG)) { - final String s; - if (keepalive > 0) { - s = "for " + (double) keepalive / 1000 + " seconds"; - } else { - s = "indefinitely"; - } - Log.d(TAG, "Connection " + format(entry) + " can be kept alive " + s); - } - } - } finally { - this.pool.release(entry, conn.isOpen() && entry.isRouteComplete()); - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Connection released: " + format(entry) + formatStats(entry.getRoute())); - } - } - } - } - - public void connect( - final HttpClientConnection managedConn, - final HttpRoute route, - final int connectTimeout, - final HttpContext context) throws IOException { - Args.notNull(managedConn, "Managed Connection"); - Args.notNull(route, "HTTP route"); - final ManagedHttpClientConnection conn; - synchronized (managedConn) { - final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn); - conn = entry.getConnection(); - } - final HttpHost host; - if (route.getProxyHost() != null) { - host = route.getProxyHost(); - } else { - host = route.getTargetHost(); - } - final InetSocketAddress localAddress = route.getLocalAddress() != null ? new InetSocketAddress(route.getLocalAddress(), 0) : null;; - SocketConfig socketConfig = this.configData.getSocketConfig(host); - if (socketConfig == null) { - socketConfig = this.configData.getDefaultSocketConfig(); - } - if (socketConfig == null) { - socketConfig = SocketConfig.DEFAULT; - } - this.connectionOperator.connect( - conn, host, localAddress, connectTimeout, socketConfig, context); - } - - public void upgrade( - final HttpClientConnection managedConn, - final HttpRoute route, - final HttpContext context) throws IOException { - Args.notNull(managedConn, "Managed Connection"); - Args.notNull(route, "HTTP route"); - final ManagedHttpClientConnection conn; - synchronized (managedConn) { - final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn); - conn = entry.getConnection(); - } - this.connectionOperator.upgrade(conn, route.getTargetHost(), context); - } - - public void routeComplete( - final HttpClientConnection managedConn, - final HttpRoute route, - final HttpContext context) throws IOException { - Args.notNull(managedConn, "Managed Connection"); - Args.notNull(route, "HTTP route"); - synchronized (managedConn) { - final CPoolEntry entry = CPoolProxy.getPoolEntry(managedConn); - entry.markRouteComplete(); - } - } - - public void shutdown() { - if (this.isShutDown.compareAndSet(false, true)) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Connection manager is shutting down"); - } - try { - this.pool.shutdown(); - } catch (final IOException ex) { - Log.d(TAG, "I/O exception shutting down connection manager", ex); - } - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Connection manager shut down"); - } - } - } - - public void closeIdleConnections(final long idleTimeout, final TimeUnit tunit) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Closing connections idle longer than " + idleTimeout + " " + tunit); - } - this.pool.closeIdle(idleTimeout, tunit); - } - - public void closeExpiredConnections() { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Closing expired connections"); - } - this.pool.closeExpired(); - } - - public int getMaxTotal() { - return this.pool.getMaxTotal(); - } - - public void setMaxTotal(final int max) { - this.pool.setMaxTotal(max); - } - - public int getDefaultMaxPerRoute() { - return this.pool.getDefaultMaxPerRoute(); - } - - public void setDefaultMaxPerRoute(final int max) { - this.pool.setDefaultMaxPerRoute(max); - } - - public int getMaxPerRoute(final HttpRoute route) { - return this.pool.getMaxPerRoute(route); - } - - public void setMaxPerRoute(final HttpRoute route, final int max) { - this.pool.setMaxPerRoute(route, max); - } - - public PoolStats getTotalStats() { - return this.pool.getTotalStats(); - } - - public PoolStats getStats(final HttpRoute route) { - return this.pool.getStats(route); - } - - public SocketConfig getDefaultSocketConfig() { - return this.configData.getDefaultSocketConfig(); - } - - public void setDefaultSocketConfig(final SocketConfig defaultSocketConfig) { - this.configData.setDefaultSocketConfig(defaultSocketConfig); - } - - public ConnectionConfig getDefaultConnectionConfig() { - return this.configData.getDefaultConnectionConfig(); - } - - public void setDefaultConnectionConfig(final ConnectionConfig defaultConnectionConfig) { - this.configData.setDefaultConnectionConfig(defaultConnectionConfig); - } - - public SocketConfig getSocketConfig(final HttpHost host) { - return this.configData.getSocketConfig(host); - } - - public void setSocketConfig(final HttpHost host, final SocketConfig socketConfig) { - this.configData.setSocketConfig(host, socketConfig); - } - - public ConnectionConfig getConnectionConfig(final HttpHost host) { - return this.configData.getConnectionConfig(host); - } - - public void setConnectionConfig(final HttpHost host, final ConnectionConfig connectionConfig) { - this.configData.setConnectionConfig(host, connectionConfig); - } - - static class ConfigData { - - private final Map socketConfigMap; - private final Map connectionConfigMap; - private volatile SocketConfig defaultSocketConfig; - private volatile ConnectionConfig defaultConnectionConfig; - - ConfigData() { - super(); - this.socketConfigMap = new ConcurrentHashMap(); - this.connectionConfigMap = new ConcurrentHashMap(); - } - - public SocketConfig getDefaultSocketConfig() { - return this.defaultSocketConfig; - } - - public void setDefaultSocketConfig(final SocketConfig defaultSocketConfig) { - this.defaultSocketConfig = defaultSocketConfig; - } - - public ConnectionConfig getDefaultConnectionConfig() { - return this.defaultConnectionConfig; - } - - public void setDefaultConnectionConfig(final ConnectionConfig defaultConnectionConfig) { - this.defaultConnectionConfig = defaultConnectionConfig; - } - - public SocketConfig getSocketConfig(final HttpHost host) { - return this.socketConfigMap.get(host); - } - - public void setSocketConfig(final HttpHost host, final SocketConfig socketConfig) { - this.socketConfigMap.put(host, socketConfig); - } - - public ConnectionConfig getConnectionConfig(final HttpHost host) { - return this.connectionConfigMap.get(host); - } - - public void setConnectionConfig(final HttpHost host, final ConnectionConfig connectionConfig) { - this.connectionConfigMap.put(host, connectionConfig); - } - - } - - static class InternalConnectionFactory implements ConnFactory { - - private final ConfigData configData; - private final HttpConnectionFactory connFactory; - - InternalConnectionFactory( - final ConfigData configData, - final HttpConnectionFactory connFactory) { - super(); - this.configData = configData != null ? configData : new ConfigData(); - this.connFactory = connFactory != null ? connFactory : - ManagedHttpClientConnectionFactory.INSTANCE; - } - - public ManagedHttpClientConnection create(final HttpRoute route) throws IOException { - ConnectionConfig config = null; - if (route.getProxyHost() != null) { - config = this.configData.getConnectionConfig(route.getProxyHost()); - } - if (config == null) { - config = this.configData.getConnectionConfig(route.getTargetHost()); - } - if (config == null) { - config = this.configData.getDefaultConnectionConfig(); - } - if (config == null) { - config = ConnectionConfig.DEFAULT; - } - return this.connFactory.create(route, config); - } - - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/SystemDefaultDnsResolver.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/SystemDefaultDnsResolver.java deleted file mode 100644 index 8b9cb6ba..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/SystemDefaultDnsResolver.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.conn; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -import org.apache.http.conn.DnsResolver; - -/** - * DNS resolver that uses the default OS implementation for resolving host names. - * - * @since 4.2 - */ -public class SystemDefaultDnsResolver implements DnsResolver { - - public static final SystemDefaultDnsResolver INSTANCE = new SystemDefaultDnsResolver(); - - public InetAddress[] resolve(final String host) throws UnknownHostException { - return InetAddress.getAllByName(host); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/SystemDefaultRoutePlanner.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/SystemDefaultRoutePlanner.java deleted file mode 100644 index 6b872b9e..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/SystemDefaultRoutePlanner.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.conn; - -import java.net.InetSocketAddress; -import java.net.Proxy; -import java.net.ProxySelector; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; - -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.annotation.Immutable; -import org.apache.http.conn.SchemePortResolver; -import org.apache.http.protocol.HttpContext; - -/** - * {@link org.apache.http.conn.routing.HttpRoutePlanner} implementation - * based on {@link ProxySelector}. By default, this class will pick up - * the proxy settings of the JVM, either from system properties - * or from the browser running the application. - * - * @since 4.3 - */ -@Immutable -public class SystemDefaultRoutePlanner extends DefaultRoutePlanner { - - private final ProxySelector proxySelector; - - public SystemDefaultRoutePlanner( - final SchemePortResolver schemePortResolver, - final ProxySelector proxySelector) { - super(schemePortResolver); - this.proxySelector = proxySelector != null ? proxySelector : ProxySelector.getDefault(); - } - - public SystemDefaultRoutePlanner(final ProxySelector proxySelector) { - this(null, proxySelector); - } - - @Override - protected HttpHost determineProxy( - final HttpHost target, - final HttpRequest request, - final HttpContext context) throws HttpException { - final URI targetURI; - try { - targetURI = new URI(target.toURI()); - } catch (final URISyntaxException ex) { - throw new HttpException("Cannot convert host to URI: " + target, ex); - } - final List proxies = this.proxySelector.select(targetURI); - final Proxy p = chooseProxy(proxies); - HttpHost result = null; - if (p.type() == Proxy.Type.HTTP) { - // convert the socket address to an HttpHost - if (!(p.address() instanceof InetSocketAddress)) { - throw new HttpException("Unable to handle non-Inet proxy address: " + p.address()); - } - final InetSocketAddress isa = (InetSocketAddress) p.address(); - // assume default scheme (http) - result = new HttpHost(getHost(isa), isa.getPort()); - } - - return result; - } - - private String getHost(final InetSocketAddress isa) { - - //@@@ Will this work with literal IPv6 addresses, or do we - //@@@ need to wrap these in [] for the string representation? - //@@@ Having it in this method at least allows for easy workarounds. - return isa.isUnresolved() ? - isa.getHostName() : isa.getAddress().getHostAddress(); - - } - - private Proxy chooseProxy(final List proxies) { - Proxy result = null; - // check the list for one we can use - for (int i=0; (result == null) && (i < proxies.size()); i++) { - final Proxy p = proxies.get(i); - switch (p.type()) { - - case DIRECT: - case HTTP: - result = p; - break; - - case SOCKS: - // SOCKS hosts are not handled on the route level. - // The socket may make use of the SOCKS host though. - break; - } - } - if (result == null) { - //@@@ log as warning or info that only a socks proxy is available? - // result can only be null if all proxies are socks proxies - // socks proxies are not handled on the route planning level - result = Proxy.NO_PROXY; - } - return result; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/WireHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/WireHC4.java deleted file mode 100644 index 6bb063b6..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/WireHC4.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.conn; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -import android.util.Log; -import org.apache.http.annotation.Immutable; -import org.apache.http.util.Args; - -/** - * Logs data to the wire LOG. - * TODO: make package private. Should not be part of the public API. - * - * @since 4.0 - */ -@Immutable -public class WireHC4 { - - private final static String TAG = "Wire"; - private final String id; - - /** - * @since 4.3 - */ - public WireHC4(final String id) { - this.id = id; - } - - private void wire(final String header, final InputStream instream) - throws IOException { - final StringBuilder buffer = new StringBuilder(); - int ch; - while ((ch = instream.read()) != -1) { - if (ch == 13) { - buffer.append("[\\r]"); - } else if (ch == 10) { - buffer.append("[\\n]\""); - buffer.insert(0, "\""); - buffer.insert(0, header); - Log.d(TAG, id + " " + buffer.toString()); - buffer.setLength(0); - } else if ((ch < 32) || (ch > 127)) { - buffer.append("[0x"); - buffer.append(Integer.toHexString(ch)); - buffer.append("]"); - } else { - buffer.append((char) ch); - } - } - if (buffer.length() > 0) { - buffer.append('\"'); - buffer.insert(0, '\"'); - buffer.insert(0, header); - Log.d(TAG, id + " " + buffer.toString()); - } - } - - - public boolean enabled() { - return Log.isLoggable(TAG, Log.DEBUG); - } - - public void output(final InputStream outstream) - throws IOException { - Args.notNull(outstream, "Output"); - wire(">> ", outstream); - } - - public void input(final InputStream instream) - throws IOException { - Args.notNull(instream, "Input"); - wire("<< ", instream); - } - - public void output(final byte[] b, final int off, final int len) - throws IOException { - Args.notNull(b, "Output"); - wire(">> ", new ByteArrayInputStream(b, off, len)); - } - - public void input(final byte[] b, final int off, final int len) - throws IOException { - Args.notNull(b, "Input"); - wire("<< ", new ByteArrayInputStream(b, off, len)); - } - - public void output(final byte[] b) - throws IOException { - Args.notNull(b, "Output"); - wire(">> ", new ByteArrayInputStream(b)); - } - - public void input(final byte[] b) - throws IOException { - Args.notNull(b, "Input"); - wire("<< ", new ByteArrayInputStream(b)); - } - - public void output(final int b) - throws IOException { - output(new byte[] {(byte) b}); - } - - public void input(final int b) - throws IOException { - input(new byte[] {(byte) b}); - } - - public void output(final String s) - throws IOException { - Args.notNull(s, "Output"); - output(s.getBytes()); - } - - public void input(final String s) - throws IOException { - Args.notNull(s, "Input"); - input(s.getBytes()); - } -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/package-info.java deleted file mode 100644 index bebf28d1..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/conn/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Default implementations of client connection management - * functions. - */ -package org.apache.http.impl.conn; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/AbstractCookieAttributeHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/AbstractCookieAttributeHandlerHC4.java deleted file mode 100644 index 893fc346..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/AbstractCookieAttributeHandlerHC4.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; - -/** - * - * @since 4.0 - */ -@Immutable -public abstract class AbstractCookieAttributeHandlerHC4 implements CookieAttributeHandler { - - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - // Do nothing - } - - public boolean match(final Cookie cookie, final CookieOrigin origin) { - // Always match - return true; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/AbstractCookieSpecHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/AbstractCookieSpecHC4.java deleted file mode 100644 index ddeda23f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/AbstractCookieSpecHC4.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieSpec; -import org.apache.http.util.Args; - -/** - * Abstract cookie specification which can delegate the job of parsing, - * validation or matching cookie attributes to a number of arbitrary - * {@link CookieAttributeHandler}s. - * - * - * @since 4.0 - */ -@NotThreadSafe // HashMap is not thread-safe -public abstract class AbstractCookieSpecHC4 implements CookieSpec { - - /** - * Stores attribute name -> attribute handler mappings - */ - private final Map attribHandlerMap; - - /** - * Default constructor - * */ - public AbstractCookieSpecHC4() { - super(); - this.attribHandlerMap = new HashMap(10); - } - - public void registerAttribHandler( - final String name, final CookieAttributeHandler handler) { - Args.notNull(name, "Attribute name"); - Args.notNull(handler, "Attribute handler"); - this.attribHandlerMap.put(name, handler); - } - - /** - * Finds an attribute handler {@link CookieAttributeHandler} for the - * given attribute. Returns null if no attribute handler is - * found for the specified attribute. - * - * @param name attribute name. e.g. Domain, Path, etc. - * @return an attribute handler or null - */ - protected CookieAttributeHandler findAttribHandler(final String name) { - return this.attribHandlerMap.get(name); - } - - /** - * Gets attribute handler {@link CookieAttributeHandler} for the - * given attribute. - * - * @param name attribute name. e.g. Domain, Path, etc. - * @throws IllegalStateException if handler not found for the - * specified attribute. - */ - protected CookieAttributeHandler getAttribHandler(final String name) { - final CookieAttributeHandler handler = findAttribHandler(name); - if (handler == null) { - throw new IllegalStateException("Handler not registered for " + - name + " attribute."); - } else { - return handler; - } - } - - protected Collection getAttribHandlers() { - return this.attribHandlerMap.values(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicClientCookie2HC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicClientCookie2HC4.java deleted file mode 100644 index 0cc86d43..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicClientCookie2HC4.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.Date; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.cookie.SetCookie2; - -/** - * Default implementation of {@link SetCookie2}. - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicClientCookie2HC4 extends BasicClientCookieHC4 implements SetCookie2 { - - private static final long serialVersionUID = -7744598295706617057L; - - private String commentURL; - private int[] ports; - private boolean discard; - - /** - * Default Constructor taking a name and a value. The value may be null. - * - * @param name The name. - * @param value The value. - */ - public BasicClientCookie2HC4(final String name, final String value) { - super(name, value); - } - - @Override - public int[] getPorts() { - return this.ports; - } - - public void setPorts(final int[] ports) { - this.ports = ports; - } - - @Override - public String getCommentURL() { - return this.commentURL; - } - - public void setCommentURL(final String commentURL) { - this.commentURL = commentURL; - } - - public void setDiscard(final boolean discard) { - this.discard = discard; - } - - @Override - public boolean isPersistent() { - return !this.discard && super.isPersistent(); - } - - @Override - public boolean isExpired(final Date date) { - return this.discard || super.isExpired(date); - } - - @Override - public Object clone() throws CloneNotSupportedException { - final BasicClientCookie2HC4 clone = (BasicClientCookie2HC4) super.clone(); - if (this.ports != null) { - clone.ports = this.ports.clone(); - } - return clone; - } - -} - diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicClientCookieHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicClientCookieHC4.java deleted file mode 100644 index cf9500b0..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicClientCookieHC4.java +++ /dev/null @@ -1,361 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.io.Serializable; -import java.util.Date; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.SetCookie; -import org.apache.http.util.Args; - -/** - * Default implementation of {@link SetCookie}. - * - * @since 4.0 - */ -@NotThreadSafe -public class BasicClientCookieHC4 implements SetCookie, ClientCookie, Cloneable, Serializable { - - private static final long serialVersionUID = -3869795591041535538L; - - /** - * Default Constructor taking a name and a value. The value may be null. - * - * @param name The name. - * @param value The value. - */ - public BasicClientCookieHC4(final String name, final String value) { - super(); - Args.notNull(name, "Name"); - this.name = name; - this.attribs = new HashMap(); - this.value = value; - } - - /** - * Returns the name. - * - * @return String name The name - */ - public String getName() { - return this.name; - } - - /** - * Returns the value. - * - * @return String value The current value. - */ - public String getValue() { - return this.value; - } - - /** - * Sets the value - * - * @param value - */ - public void setValue(final String value) { - this.value = value; - } - - /** - * Returns the comment describing the purpose of this cookie, or - * null if no such comment has been defined. - * - * @return comment - * - * @see #setComment(String) - */ - public String getComment() { - return cookieComment; - } - - /** - * If a user agent (web browser) presents this cookie to a user, the - * cookie's purpose will be described using this comment. - * - * @param comment - * - * @see #getComment() - */ - public void setComment(final String comment) { - cookieComment = comment; - } - - - /** - * Returns null. Cookies prior to RFC2965 do not set this attribute - */ - public String getCommentURL() { - return null; - } - - - /** - * Returns the expiration {@link Date} of the cookie, or null - * if none exists. - *

    Note: the object returned by this method is - * considered immutable. Changing it (e.g. using setTime()) could result - * in undefined behaviour. Do so at your peril.

    - * @return Expiration {@link Date}, or null. - * - * @see #setExpiryDate(java.util.Date) - * - */ - public Date getExpiryDate() { - return cookieExpiryDate; - } - - /** - * Sets expiration date. - *

    Note: the object returned by this method is considered - * immutable. Changing it (e.g. using setTime()) could result in undefined - * behaviour. Do so at your peril.

    - * - * @param expiryDate the {@link Date} after which this cookie is no longer valid. - * - * @see #getExpiryDate - * - */ - public void setExpiryDate (final Date expiryDate) { - cookieExpiryDate = expiryDate; - } - - - /** - * Returns false if the cookie should be discarded at the end - * of the "session"; true otherwise. - * - * @return false if the cookie should be discarded at the end - * of the "session"; true otherwise - */ - public boolean isPersistent() { - return (null != cookieExpiryDate); - } - - - /** - * Returns domain attribute of the cookie. - * - * @return the value of the domain attribute - * - * @see #setDomain(java.lang.String) - */ - public String getDomain() { - return cookieDomain; - } - - /** - * Sets the domain attribute. - * - * @param domain The value of the domain attribute - * - * @see #getDomain - */ - public void setDomain(final String domain) { - if (domain != null) { - cookieDomain = domain.toLowerCase(Locale.ENGLISH); - } else { - cookieDomain = null; - } - } - - - /** - * Returns the path attribute of the cookie - * - * @return The value of the path attribute. - * - * @see #setPath(java.lang.String) - */ - public String getPath() { - return cookiePath; - } - - /** - * Sets the path attribute. - * - * @param path The value of the path attribute - * - * @see #getPath - * - */ - public void setPath(final String path) { - cookiePath = path; - } - - /** - * @return true if this cookie should only be sent over secure connections. - * @see #setSecure(boolean) - */ - public boolean isSecure() { - return isSecure; - } - - /** - * Sets the secure attribute of the cookie. - *

    - * When true the cookie should only be sent - * using a secure protocol (https). This should only be set when - * the cookie's originating server used a secure protocol to set the - * cookie's value. - * - * @param secure The value of the secure attribute - * - * @see #isSecure() - */ - public void setSecure (final boolean secure) { - isSecure = secure; - } - - - /** - * Returns null. Cookies prior to RFC2965 do not set this attribute - */ - public int[] getPorts() { - return null; - } - - - /** - * Returns the version of the cookie specification to which this - * cookie conforms. - * - * @return the version of the cookie. - * - * @see #setVersion(int) - * - */ - public int getVersion() { - return cookieVersion; - } - - /** - * Sets the version of the cookie specification to which this - * cookie conforms. - * - * @param version the version of the cookie. - * - * @see #getVersion - */ - public void setVersion(final int version) { - cookieVersion = version; - } - - /** - * Returns true if this cookie has expired. - * @param date Current time - * - * @return true if the cookie has expired. - */ - public boolean isExpired(final Date date) { - Args.notNull(date, "Date"); - return (cookieExpiryDate != null - && cookieExpiryDate.getTime() <= date.getTime()); - } - - public void setAttribute(final String name, final String value) { - this.attribs.put(name, value); - } - - public String getAttribute(final String name) { - return this.attribs.get(name); - } - - public boolean containsAttribute(final String name) { - return this.attribs.get(name) != null; - } - - @Override - public Object clone() throws CloneNotSupportedException { - final BasicClientCookieHC4 clone = (BasicClientCookieHC4) super.clone(); - clone.attribs = new HashMap(this.attribs); - return clone; - } - - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append("[version: "); - buffer.append(Integer.toString(this.cookieVersion)); - buffer.append("]"); - buffer.append("[name: "); - buffer.append(this.name); - buffer.append("]"); - buffer.append("[value: "); - buffer.append(this.value); - buffer.append("]"); - buffer.append("[domain: "); - buffer.append(this.cookieDomain); - buffer.append("]"); - buffer.append("[path: "); - buffer.append(this.cookiePath); - buffer.append("]"); - buffer.append("[expiry: "); - buffer.append(this.cookieExpiryDate); - buffer.append("]"); - return buffer.toString(); - } - - // ----------------------------------------------------- Instance Variables - - /** Cookie name */ - private final String name; - - /** Cookie attributes as specified by the origin server */ - private Map attribs; - - /** Cookie value */ - private String value; - - /** Comment attribute. */ - private String cookieComment; - - /** Domain attribute. */ - private String cookieDomain; - - /** Expiration {@link Date}. */ - private Date cookieExpiryDate; - - /** Path attribute. */ - private String cookiePath; - - /** My secure flag. */ - private boolean isSecure; - - /** The version of the cookie specification I was created from. */ - private int cookieVersion; - -} - diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicCommentHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicCommentHandlerHC4.java deleted file mode 100644 index f55bfd2e..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicCommentHandlerHC4.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; -import org.apache.http.util.Args; - -/** - * - * @since 4.0 - */ -@Immutable -public class BasicCommentHandlerHC4 extends AbstractCookieAttributeHandlerHC4 { - - public BasicCommentHandlerHC4() { - super(); - } - - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - cookie.setComment(value); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicDomainHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicDomainHandlerHC4.java deleted file mode 100644 index 87a5723e..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicDomainHandlerHC4.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.CookieRestrictionViolationException; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; -import org.apache.http.util.Args; - -/** - * - * @since 4.0 - */ -@Immutable -public class BasicDomainHandlerHC4 implements CookieAttributeHandler { - - public BasicDomainHandlerHC4() { - super(); - } - - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (value == null) { - throw new MalformedCookieException("Missing value for domain attribute"); - } - if (value.trim().length() == 0) { - throw new MalformedCookieException("Blank value for domain attribute"); - } - cookie.setDomain(value); - } - - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - // Validate the cookies domain attribute. NOTE: Domains without - // any dots are allowed to support hosts on private LANs that don't - // have DNS names. Since they have no dots, to domain-match the - // request-host and domain must be identical for the cookie to sent - // back to the origin-server. - final String host = origin.getHost(); - String domain = cookie.getDomain(); - if (domain == null) { - throw new CookieRestrictionViolationException("Cookie domain may not be null"); - } - if (host.contains(".")) { - // Not required to have at least two dots. RFC 2965. - // A Set-Cookie2 with Domain=ajax.com will be accepted. - - // domain must match host - if (!host.endsWith(domain)) { - if (domain.startsWith(".")) { - domain = domain.substring(1, domain.length()); - } - if (!host.equals(domain)) { - throw new CookieRestrictionViolationException( - "Illegal domain attribute \"" + domain - + "\". Domain of origin: \"" + host + "\""); - } - } - } else { - if (!host.equals(domain)) { - throw new CookieRestrictionViolationException( - "Illegal domain attribute \"" + domain - + "\". Domain of origin: \"" + host + "\""); - } - } - } - - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - final String host = origin.getHost(); - String domain = cookie.getDomain(); - if (domain == null) { - return false; - } - if (host.equals(domain)) { - return true; - } - if (!domain.startsWith(".")) { - domain = '.' + domain; - } - return host.endsWith(domain) || host.equals(domain.substring(1)); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicExpiresHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicExpiresHandlerHC4.java deleted file mode 100644 index 8b691eda..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicExpiresHandlerHC4.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import java.util.Date; - -import org.apache.http.annotation.Immutable; -import org.apache.http.client.utils.DateUtils; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; -import org.apache.http.util.Args; - -/** - * - * @since 4.0 - */ -@Immutable -public class BasicExpiresHandlerHC4 extends AbstractCookieAttributeHandlerHC4 { - - /** Valid date patterns */ - private final String[] datepatterns; - - public BasicExpiresHandlerHC4(final String[] datepatterns) { - Args.notNull(datepatterns, "Array of date patterns"); - this.datepatterns = datepatterns; - } - - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (value == null) { - throw new MalformedCookieException("Missing value for expires attribute"); - } - final Date expiry = DateUtils.parseDate(value, this.datepatterns); - if (expiry == null) { - throw new MalformedCookieException("Unable to parse expires attribute: " - + value); - } - cookie.setExpiryDate(expiry); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicMaxAgeHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicMaxAgeHandlerHC4.java deleted file mode 100644 index 75cfdf38..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicMaxAgeHandlerHC4.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import java.util.Date; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; -import org.apache.http.util.Args; - -/** - * - * @since 4.0 - */ -@Immutable -public class BasicMaxAgeHandlerHC4 extends AbstractCookieAttributeHandlerHC4 { - - public BasicMaxAgeHandlerHC4() { - super(); - } - - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (value == null) { - throw new MalformedCookieException("Missing value for max-age attribute"); - } - final int age; - try { - age = Integer.parseInt(value); - } catch (final NumberFormatException e) { - throw new MalformedCookieException ("Invalid max-age attribute: " - + value); - } - if (age < 0) { - throw new MalformedCookieException ("Negative max-age attribute: " - + value); - } - cookie.setExpiryDate(new Date(System.currentTimeMillis() + age * 1000L)); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicPathHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicPathHandlerHC4.java deleted file mode 100644 index 5326a183..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicPathHandlerHC4.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.CookieRestrictionViolationException; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; -import org.apache.http.util.Args; -import org.apache.http.util.TextUtils; - -/** - * - * @since 4.0 - */ -@Immutable -public class BasicPathHandlerHC4 implements CookieAttributeHandler { - - public BasicPathHandlerHC4() { - super(); - } - - public void parse( - final SetCookie cookie, final String value) throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - cookie.setPath(!TextUtils.isBlank(value) ? value : "/"); - } - - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - if (!match(cookie, origin)) { - throw new CookieRestrictionViolationException( - "Illegal path attribute \"" + cookie.getPath() - + "\". Path of origin: \"" + origin.getPath() + "\""); - } - } - - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - final String targetpath = origin.getPath(); - String topmostPath = cookie.getPath(); - if (topmostPath == null) { - topmostPath = "/"; - } - if (topmostPath.length() > 1 && topmostPath.endsWith("/")) { - topmostPath = topmostPath.substring(0, topmostPath.length() - 1); - } - boolean match = targetpath.startsWith (topmostPath); - // if there is a match and these values are not exactly the same we have - // to make sure we're not matcing "/foobar" and "/foo" - if (match && targetpath.length() != topmostPath.length()) { - if (!topmostPath.endsWith("/")) { - match = (targetpath.charAt(topmostPath.length()) == '/'); - } - } - return match; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicSecureHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicSecureHandlerHC4.java deleted file mode 100644 index ca091ad9..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BasicSecureHandlerHC4.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; -import org.apache.http.util.Args; - -/** - * - * @since 4.0 - */ -@Immutable -public class BasicSecureHandlerHC4 extends AbstractCookieAttributeHandlerHC4 { - - public BasicSecureHandlerHC4() { - super(); - } - - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - cookie.setSecure(true); - } - - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - return !cookie.isSecure() || origin.isSecure(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BestMatchSpecFactoryHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BestMatchSpecFactoryHC4.java deleted file mode 100644 index c92ea539..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BestMatchSpecFactoryHC4.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.Collection; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.CookieSpec; -import org.apache.http.cookie.CookieSpecFactory; -import org.apache.http.cookie.CookieSpecProvider; -import org.apache.http.cookie.params.CookieSpecPNames; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HttpContext; - -/** - * {@link CookieSpecProvider} implementation that creates and initializes - * {@link BestMatchSpec} instances. - * - * @since 4.0 - */ -@Immutable -@SuppressWarnings("deprecation") -public class BestMatchSpecFactoryHC4 implements CookieSpecFactory, CookieSpecProvider { - - private final String[] datepatterns; - private final boolean oneHeader; - - public BestMatchSpecFactoryHC4(final String[] datepatterns, final boolean oneHeader) { - super(); - this.datepatterns = datepatterns; - this.oneHeader = oneHeader; - } - - public BestMatchSpecFactoryHC4() { - this(null, false); - } - - public CookieSpec newInstance(final HttpParams params) { - if (params != null) { - - String[] patterns = null; - final Collection param = (Collection) params.getParameter( - CookieSpecPNames.DATE_PATTERNS); - if (param != null) { - patterns = new String[param.size()]; - patterns = param.toArray(patterns); - } - final boolean singleHeader = params.getBooleanParameter( - CookieSpecPNames.SINGLE_COOKIE_HEADER, false); - - return new BestMatchSpecHC4(patterns, singleHeader); - } else { - return new BestMatchSpecHC4(); - } - } - - public CookieSpec create(final HttpContext context) { - return new BestMatchSpecHC4(this.datepatterns, this.oneHeader); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BestMatchSpecHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BestMatchSpecHC4.java deleted file mode 100644 index b8518f21..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BestMatchSpecHC4.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.List; - -import org.apache.http.FormattedHeader; -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.CookieSpec; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SM; -import org.apache.http.cookie.SetCookie2; -import org.apache.http.message.ParserCursor; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * 'Meta' cookie specification that picks up a cookie policy based on - * the format of cookies sent with the HTTP response. - * - * @since 4.0 - */ -@NotThreadSafe // CookieSpec fields are @NotThreadSafe -public class BestMatchSpecHC4 implements CookieSpec { - - private final String[] datepatterns; - private final boolean oneHeader; - - // Cached values of CookieSpec instances - private RFC2965SpecHC4 strict; // @NotThreadSafe - private RFC2109SpecHC4 obsoleteStrict; // @NotThreadSafe - private BrowserCompatSpecHC4 compat; // @NotThreadSafe - - public BestMatchSpecHC4(final String[] datepatterns, final boolean oneHeader) { - super(); - this.datepatterns = datepatterns == null ? null : datepatterns.clone(); - this.oneHeader = oneHeader; - } - - public BestMatchSpecHC4() { - this(null, false); - } - - private RFC2965SpecHC4 getStrict() { - if (this.strict == null) { - this.strict = new RFC2965SpecHC4(this.datepatterns, this.oneHeader); - } - return strict; - } - - private RFC2109SpecHC4 getObsoleteStrict() { - if (this.obsoleteStrict == null) { - this.obsoleteStrict = new RFC2109SpecHC4(this.datepatterns, this.oneHeader); - } - return obsoleteStrict; - } - - private BrowserCompatSpecHC4 getCompat() { - if (this.compat == null) { - this.compat = new BrowserCompatSpecHC4(this.datepatterns); - } - return compat; - } - - public List parse( - final Header header, - final CookieOrigin origin) throws MalformedCookieException { - Args.notNull(header, "Header"); - Args.notNull(origin, "Cookie origin"); - HeaderElement[] helems = header.getElements(); - boolean versioned = false; - boolean netscape = false; - for (final HeaderElement helem: helems) { - if (helem.getParameterByName("version") != null) { - versioned = true; - } - if (helem.getParameterByName("expires") != null) { - netscape = true; - } - } - if (netscape || !versioned) { - // Need to parse the header again, because Netscape style cookies do not correctly - // support multiple header elements (comma cannot be treated as an element separator) - final NetscapeDraftHeaderParserHC4 parser = NetscapeDraftHeaderParserHC4.DEFAULT; - final CharArrayBuffer buffer; - final ParserCursor cursor; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - cursor = new ParserCursor( - ((FormattedHeader) header).getValuePos(), - buffer.length()); - } else { - final String s = header.getValue(); - if (s == null) { - throw new MalformedCookieException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - cursor = new ParserCursor(0, buffer.length()); - } - helems = new HeaderElement[] { parser.parseHeader(buffer, cursor) }; - return getCompat().parse(helems, origin); - } else { - if (SM.SET_COOKIE2.equals(header.getName())) { - return getStrict().parse(helems, origin); - } else { - return getObsoleteStrict().parse(helems, origin); - } - } - } - - public void validate( - final Cookie cookie, - final CookieOrigin origin) throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - if (cookie.getVersion() > 0) { - if (cookie instanceof SetCookie2) { - getStrict().validate(cookie, origin); - } else { - getObsoleteStrict().validate(cookie, origin); - } - } else { - getCompat().validate(cookie, origin); - } - } - - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - if (cookie.getVersion() > 0) { - if (cookie instanceof SetCookie2) { - return getStrict().match(cookie, origin); - } else { - return getObsoleteStrict().match(cookie, origin); - } - } else { - return getCompat().match(cookie, origin); - } - } - - public List

    formatCookies(final List cookies) { - Args.notNull(cookies, "List of cookies"); - int version = Integer.MAX_VALUE; - boolean isSetCookie2 = true; - for (final Cookie cookie: cookies) { - if (!(cookie instanceof SetCookie2)) { - isSetCookie2 = false; - } - if (cookie.getVersion() < version) { - version = cookie.getVersion(); - } - } - if (version > 0) { - if (isSetCookie2) { - return getStrict().formatCookies(cookies); - } else { - return getObsoleteStrict().formatCookies(cookies); - } - } else { - return getCompat().formatCookies(cookies); - } - } - - public int getVersion() { - return getStrict().getVersion(); - } - - public Header getVersionHeader() { - return getStrict().getVersionHeader(); - } - - @Override - public String toString() { - return "best-match"; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpecFactoryHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpecFactoryHC4.java deleted file mode 100644 index db2a9074..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpecFactoryHC4.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.Collection; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.CookieSpec; -import org.apache.http.cookie.CookieSpecFactory; -import org.apache.http.cookie.CookieSpecProvider; -import org.apache.http.cookie.params.CookieSpecPNames; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HttpContext; - -/** - * {@link CookieSpecProvider} implementation that creates and initializes - * {@link BrowserCompatSpec} instances. - * - * @since 4.0 - */ -@Immutable -@SuppressWarnings("deprecation") -public class BrowserCompatSpecFactoryHC4 implements CookieSpecFactory, CookieSpecProvider { - - public enum SecurityLevel { - SECURITYLEVEL_DEFAULT, - SECURITYLEVEL_IE_MEDIUM - } - - private final String[] datepatterns; - private final SecurityLevel securityLevel; - - public BrowserCompatSpecFactoryHC4(final String[] datepatterns, final SecurityLevel securityLevel) { - super(); - this.datepatterns = datepatterns; - this.securityLevel = securityLevel; - } - - public BrowserCompatSpecFactoryHC4(final String[] datepatterns) { - this(null, SecurityLevel.SECURITYLEVEL_DEFAULT); - } - - public BrowserCompatSpecFactoryHC4() { - this(null, SecurityLevel.SECURITYLEVEL_DEFAULT); - } - - public CookieSpec newInstance(final HttpParams params) { - if (params != null) { - - String[] patterns = null; - final Collection param = (Collection) params.getParameter( - CookieSpecPNames.DATE_PATTERNS); - if (param != null) { - patterns = new String[param.size()]; - patterns = param.toArray(patterns); - } - return new BrowserCompatSpecHC4(patterns, securityLevel); - } else { - return new BrowserCompatSpecHC4(null, securityLevel); - } - } - - public CookieSpec create(final HttpContext context) { - return new BrowserCompatSpecHC4(this.datepatterns); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpecHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpecHC4.java deleted file mode 100644 index f8dcab3c..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpecHC4.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.http.FormattedHeader; -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.client.utils.DateUtils; -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SM; -import org.apache.http.message.BasicHeaderElement; -import org.apache.http.message.BasicHeaderValueFormatterHC4; -import org.apache.http.message.BufferedHeader; -import org.apache.http.message.ParserCursor; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - - -/** - * Cookie specification that strives to closely mimic (mis)behavior of - * common web browser applications such as Microsoft Internet Explorer - * and Mozilla FireFox. - * - * - * @since 4.0 - */ -@NotThreadSafe // superclass is @NotThreadSafe -public class BrowserCompatSpecHC4 extends CookieSpecBaseHC4 { - - - private static final String[] DEFAULT_DATE_PATTERNS = new String[] { - DateUtils.PATTERN_RFC1123, - DateUtils.PATTERN_RFC1036, - DateUtils.PATTERN_ASCTIME, - "EEE, dd-MMM-yyyy HH:mm:ss z", - "EEE, dd-MMM-yyyy HH-mm-ss z", - "EEE, dd MMM yy HH:mm:ss z", - "EEE dd-MMM-yyyy HH:mm:ss z", - "EEE dd MMM yyyy HH:mm:ss z", - "EEE dd-MMM-yyyy HH-mm-ss z", - "EEE dd-MMM-yy HH:mm:ss z", - "EEE dd MMM yy HH:mm:ss z", - "EEE,dd-MMM-yy HH:mm:ss z", - "EEE,dd-MMM-yyyy HH:mm:ss z", - "EEE, dd-MM-yyyy HH:mm:ss z", - }; - - private final String[] datepatterns; - - /** Default constructor */ - public BrowserCompatSpecHC4(final String[] datepatterns, final BrowserCompatSpecFactoryHC4.SecurityLevel securityLevel) { - super(); - if (datepatterns != null) { - this.datepatterns = datepatterns.clone(); - } else { - this.datepatterns = DEFAULT_DATE_PATTERNS; - } - switch (securityLevel) { - case SECURITYLEVEL_DEFAULT: - registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandlerHC4()); - break; - case SECURITYLEVEL_IE_MEDIUM: - registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandlerHC4() { - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { - // No validation - } - } - ); - break; - default: - throw new RuntimeException("Unknown security level"); - } - - registerAttribHandler(ClientCookie.DOMAIN_ATTR, new BasicDomainHandlerHC4()); - registerAttribHandler(ClientCookie.MAX_AGE_ATTR, new BasicMaxAgeHandlerHC4()); - registerAttribHandler(ClientCookie.SECURE_ATTR, new BasicSecureHandlerHC4()); - registerAttribHandler(ClientCookie.COMMENT_ATTR, new BasicCommentHandlerHC4()); - registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandlerHC4( - this.datepatterns)); - registerAttribHandler(ClientCookie.VERSION_ATTR, new BrowserCompatVersionAttributeHandler()); - } - - /** Default constructor */ - public BrowserCompatSpecHC4(final String[] datepatterns) { - this(datepatterns, BrowserCompatSpecFactoryHC4.SecurityLevel.SECURITYLEVEL_DEFAULT); - } - - /** Default constructor */ - public BrowserCompatSpecHC4() { - this(null, BrowserCompatSpecFactoryHC4.SecurityLevel.SECURITYLEVEL_DEFAULT); - } - - public List parse(final Header header, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(header, "Header"); - Args.notNull(origin, "Cookie origin"); - final String headername = header.getName(); - if (!headername.equalsIgnoreCase(SM.SET_COOKIE)) { - throw new MalformedCookieException("Unrecognized cookie header '" - + header.toString() + "'"); - } - HeaderElement[] helems = header.getElements(); - boolean versioned = false; - boolean netscape = false; - for (final HeaderElement helem: helems) { - if (helem.getParameterByName("version") != null) { - versioned = true; - } - if (helem.getParameterByName("expires") != null) { - netscape = true; - } - } - if (netscape || !versioned) { - // Need to parse the header again, because Netscape style cookies do not correctly - // support multiple header elements (comma cannot be treated as an element separator) - final NetscapeDraftHeaderParserHC4 parser = NetscapeDraftHeaderParserHC4.DEFAULT; - final CharArrayBuffer buffer; - final ParserCursor cursor; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - cursor = new ParserCursor( - ((FormattedHeader) header).getValuePos(), - buffer.length()); - } else { - final String s = header.getValue(); - if (s == null) { - throw new MalformedCookieException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - cursor = new ParserCursor(0, buffer.length()); - } - helems = new HeaderElement[] { parser.parseHeader(buffer, cursor) }; - } - return parse(helems, origin); - } - - private static boolean isQuoteEnclosed(final String s) { - return s != null && s.startsWith("\"") && s.endsWith("\""); - } - - public List
    formatCookies(final List cookies) { - Args.notEmpty(cookies, "List of cookies"); - final CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size()); - buffer.append(SM.COOKIE); - buffer.append(": "); - for (int i = 0; i < cookies.size(); i++) { - final Cookie cookie = cookies.get(i); - if (i > 0) { - buffer.append("; "); - } - final String cookieName = cookie.getName(); - final String cookieValue = cookie.getValue(); - if (cookie.getVersion() > 0 && !isQuoteEnclosed(cookieValue)) { - BasicHeaderValueFormatterHC4.INSTANCE.formatHeaderElement( - buffer, - new BasicHeaderElement(cookieName, cookieValue), - false); - } else { - // Netscape style cookies do not support quoted values - buffer.append(cookieName); - buffer.append("="); - if (cookieValue != null) { - buffer.append(cookieValue); - } - } - } - final List
    headers = new ArrayList
    (1); - headers.add(new BufferedHeader(buffer)); - return headers; - } - - public int getVersion() { - return 0; - } - - public Header getVersionHeader() { - return null; - } - - @Override - public String toString() { - return "compatibility"; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BrowserCompatVersionAttributeHandler.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BrowserCompatVersionAttributeHandler.java deleted file mode 100644 index 2baa2670..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/BrowserCompatVersionAttributeHandler.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; -import org.apache.http.util.Args; - -/** - * "Version" cookie attribute handler for BrowserCompat cookie spec. - * - * @since 4.3 - */ -@Immutable -public class BrowserCompatVersionAttributeHandler extends - AbstractCookieAttributeHandlerHC4 { - - public BrowserCompatVersionAttributeHandler() { - super(); - } - - /** - * Parse cookie version attribute. - */ - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (value == null) { - throw new MalformedCookieException("Missing value for version attribute"); - } - int version = 0; - try { - version = Integer.parseInt(value); - } catch (final NumberFormatException e) { - // Just ignore invalid versions - } - cookie.setVersion(version); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/CookieSpecBaseHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/CookieSpecBaseHC4.java deleted file mode 100644 index b32f1fae..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/CookieSpecBaseHC4.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.apache.http.HeaderElement; -import org.apache.http.NameValuePair; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.util.Args; - -/** - * Cookie management functions shared by all specification. - * - * - * @since 4.0 - */ -@NotThreadSafe // AbstractCookieSpecHC4 is not thread-safe -public abstract class CookieSpecBaseHC4 extends AbstractCookieSpecHC4 { - - protected static String getDefaultPath(final CookieOrigin origin) { - String defaultPath = origin.getPath(); - int lastSlashIndex = defaultPath.lastIndexOf('/'); - if (lastSlashIndex >= 0) { - if (lastSlashIndex == 0) { - //Do not remove the very first slash - lastSlashIndex = 1; - } - defaultPath = defaultPath.substring(0, lastSlashIndex); - } - return defaultPath; - } - - protected static String getDefaultDomain(final CookieOrigin origin) { - return origin.getHost(); - } - - protected List parse(final HeaderElement[] elems, final CookieOrigin origin) - throws MalformedCookieException { - final List cookies = new ArrayList(elems.length); - for (final HeaderElement headerelement : elems) { - final String name = headerelement.getName(); - final String value = headerelement.getValue(); - if (name == null || name.length() == 0) { - throw new MalformedCookieException("Cookie name may not be empty"); - } - - final BasicClientCookieHC4 cookie = new BasicClientCookieHC4(name, value); - cookie.setPath(getDefaultPath(origin)); - cookie.setDomain(getDefaultDomain(origin)); - - // cycle through the parameters - final NameValuePair[] attribs = headerelement.getParameters(); - for (int j = attribs.length - 1; j >= 0; j--) { - final NameValuePair attrib = attribs[j]; - final String s = attrib.getName().toLowerCase(Locale.ENGLISH); - - cookie.setAttribute(s, attrib.getValue()); - - final CookieAttributeHandler handler = findAttribHandler(s); - if (handler != null) { - handler.parse(cookie, attrib.getValue()); - } - } - cookies.add(cookie); - } - return cookies; - } - - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - for (final CookieAttributeHandler handler: getAttribHandlers()) { - handler.validate(cookie, origin); - } - } - - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - for (final CookieAttributeHandler handler: getAttribHandlers()) { - if (!handler.match(cookie, origin)) { - return false; - } - } - return true; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/IgnoreSpec.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/IgnoreSpec.java deleted file mode 100644 index 46dde65f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/IgnoreSpec.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.Collections; -import java.util.List; - -import org.apache.http.Header; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; - -/** - * CookieSpec that ignores all cookies - * - * @since 4.1 - */ -@NotThreadSafe // superclass is @NotThreadSafe -public class IgnoreSpec extends CookieSpecBaseHC4 { - - public int getVersion() { - return 0; - } - - public List parse(final Header header, final CookieOrigin origin) - throws MalformedCookieException { - return Collections.emptyList(); - } - - public List
    formatCookies(final List cookies) { - return Collections.emptyList(); - } - - public Header getVersionHeader() { - return null; - } -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/IgnoreSpecFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/IgnoreSpecFactory.java deleted file mode 100644 index 51c7951c..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/IgnoreSpecFactory.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.CookieSpec; -import org.apache.http.cookie.CookieSpecFactory; -import org.apache.http.cookie.CookieSpecProvider; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HttpContext; - -/** - * {@link CookieSpecProvider} implementation that ignores all cookies. - * - * @since 4.1 - */ -@Immutable -@SuppressWarnings("deprecation") -public class IgnoreSpecFactory implements CookieSpecFactory, CookieSpecProvider { - - public IgnoreSpecFactory() { - super(); - } - - public CookieSpec newInstance(final HttpParams params) { - return new IgnoreSpec(); - } - - public CookieSpec create(final HttpContext context) { - return new IgnoreSpec(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/NetscapeDomainHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/NetscapeDomainHandlerHC4.java deleted file mode 100644 index c0b6eed0..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/NetscapeDomainHandlerHC4.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import java.util.Locale; -import java.util.StringTokenizer; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.CookieRestrictionViolationException; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.util.Args; - -/** - * - * @since 4.0 - */ -@Immutable -public class NetscapeDomainHandlerHC4 extends BasicDomainHandlerHC4 { - - public NetscapeDomainHandlerHC4() { - super(); - } - - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - super.validate(cookie, origin); - // Perform Netscape Cookie draft specific validation - final String host = origin.getHost(); - final String domain = cookie.getDomain(); - if (host.contains(".")) { - final int domainParts = new StringTokenizer(domain, ".").countTokens(); - - if (isSpecialDomain(domain)) { - if (domainParts < 2) { - throw new CookieRestrictionViolationException("Domain attribute \"" - + domain - + "\" violates the Netscape cookie specification for " - + "special domains"); - } - } else { - if (domainParts < 3) { - throw new CookieRestrictionViolationException("Domain attribute \"" - + domain - + "\" violates the Netscape cookie specification"); - } - } - } - } - - /** - * Checks if the given domain is in one of the seven special - * top level domains defined by the Netscape cookie specification. - * @param domain The domain. - * @return True if the specified domain is "special" - */ - private static boolean isSpecialDomain(final String domain) { - final String ucDomain = domain.toUpperCase(Locale.ENGLISH); - return ucDomain.endsWith(".COM") - || ucDomain.endsWith(".EDU") - || ucDomain.endsWith(".NET") - || ucDomain.endsWith(".GOV") - || ucDomain.endsWith(".MIL") - || ucDomain.endsWith(".ORG") - || ucDomain.endsWith(".INT"); - } - - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - final String host = origin.getHost(); - final String domain = cookie.getDomain(); - if (domain == null) { - return false; - } - return host.endsWith(domain); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/NetscapeDraftHeaderParserHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/NetscapeDraftHeaderParserHC4.java deleted file mode 100644 index fd1b756a..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/NetscapeDraftHeaderParserHC4.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.http.HeaderElement; -import org.apache.http.NameValuePair; -import org.apache.http.ParseException; -import org.apache.http.annotation.Immutable; -import org.apache.http.message.BasicHeaderElement; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.message.ParserCursor; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * - * @since 4.0 - */ -@Immutable -public class NetscapeDraftHeaderParserHC4 { - - public final static NetscapeDraftHeaderParserHC4 DEFAULT = new NetscapeDraftHeaderParserHC4(); - - public NetscapeDraftHeaderParserHC4() { - super(); - } - - public HeaderElement parseHeader( - final CharArrayBuffer buffer, - final ParserCursor cursor) throws ParseException { - Args.notNull(buffer, "Char array buffer"); - Args.notNull(cursor, "Parser cursor"); - final NameValuePair nvp = parseNameValuePair(buffer, cursor); - final List params = new ArrayList(); - while (!cursor.atEnd()) { - final NameValuePair param = parseNameValuePair(buffer, cursor); - params.add(param); - } - return new BasicHeaderElement( - nvp.getName(), - nvp.getValue(), params.toArray(new NameValuePair[params.size()])); - } - - private NameValuePair parseNameValuePair( - final CharArrayBuffer buffer, final ParserCursor cursor) { - boolean terminated = false; - - int pos = cursor.getPos(); - final int indexFrom = cursor.getPos(); - final int indexTo = cursor.getUpperBound(); - - // Find name - String name = null; - while (pos < indexTo) { - final char ch = buffer.charAt(pos); - if (ch == '=') { - break; - } - if (ch == ';') { - terminated = true; - break; - } - pos++; - } - - if (pos == indexTo) { - terminated = true; - name = buffer.substringTrimmed(indexFrom, indexTo); - } else { - name = buffer.substringTrimmed(indexFrom, pos); - pos++; - } - - if (terminated) { - cursor.updatePos(pos); - return new BasicNameValuePair(name, null); - } - - // Find value - String value = null; - int i1 = pos; - - while (pos < indexTo) { - final char ch = buffer.charAt(pos); - if (ch == ';') { - terminated = true; - break; - } - pos++; - } - - int i2 = pos; - // Trim leading white spaces - while (i1 < i2 && (HTTP.isWhitespace(buffer.charAt(i1)))) { - i1++; - } - // Trim trailing white spaces - while ((i2 > i1) && (HTTP.isWhitespace(buffer.charAt(i2 - 1)))) { - i2--; - } - value = buffer.substring(i1, i2); - if (terminated) { - pos++; - } - cursor.updatePos(pos); - return new BasicNameValuePair(name, value); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/NetscapeDraftSpecFactoryHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/NetscapeDraftSpecFactoryHC4.java deleted file mode 100644 index caf6a310..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/NetscapeDraftSpecFactoryHC4.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.Collection; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.CookieSpec; -import org.apache.http.cookie.CookieSpecFactory; -import org.apache.http.cookie.CookieSpecProvider; -import org.apache.http.cookie.params.CookieSpecPNames; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HttpContext; - -/** - * {@link CookieSpecProvider} implementation that creates and initializes - * {@link NetscapeDraftSpec} instances. - * - * @since 4.0 - */ -@Immutable -@SuppressWarnings("deprecation") -public class NetscapeDraftSpecFactoryHC4 implements CookieSpecFactory, CookieSpecProvider { - - private final String[] datepatterns; - - public NetscapeDraftSpecFactoryHC4(final String[] datepatterns) { - super(); - this.datepatterns = datepatterns; - } - - public NetscapeDraftSpecFactoryHC4() { - this(null); - } - - public CookieSpec newInstance(final HttpParams params) { - if (params != null) { - - String[] patterns = null; - final Collection param = (Collection) params.getParameter( - CookieSpecPNames.DATE_PATTERNS); - if (param != null) { - patterns = new String[param.size()]; - patterns = param.toArray(patterns); - } - return new NetscapeDraftSpecHC4(patterns); - } else { - return new NetscapeDraftSpecHC4(); - } - } - - public CookieSpec create(final HttpContext context) { - return new NetscapeDraftSpecHC4(this.datepatterns); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/NetscapeDraftSpecHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/NetscapeDraftSpecHC4.java deleted file mode 100644 index 1f5223bb..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/NetscapeDraftSpecHC4.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.http.FormattedHeader; -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SM; -import org.apache.http.message.BufferedHeader; -import org.apache.http.message.ParserCursor; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * This {@link org.apache.http.cookie.CookieSpec} implementation conforms to - * the original draft specification published by Netscape Communications. - * It should be avoided unless absolutely necessary for compatibility with - * legacy applications. - * - * @since 4.0 - */ -@NotThreadSafe // superclass is @NotThreadSafe -public class NetscapeDraftSpecHC4 extends CookieSpecBaseHC4 { - - protected static final String EXPIRES_PATTERN = "EEE, dd-MMM-yy HH:mm:ss z"; - - private final String[] datepatterns; - - /** Default constructor */ - public NetscapeDraftSpecHC4(final String[] datepatterns) { - super(); - if (datepatterns != null) { - this.datepatterns = datepatterns.clone(); - } else { - this.datepatterns = new String[] { EXPIRES_PATTERN }; - } - registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandlerHC4()); - registerAttribHandler(ClientCookie.DOMAIN_ATTR, new NetscapeDomainHandlerHC4()); - registerAttribHandler(ClientCookie.MAX_AGE_ATTR, new BasicMaxAgeHandlerHC4()); - registerAttribHandler(ClientCookie.SECURE_ATTR, new BasicSecureHandlerHC4()); - registerAttribHandler(ClientCookie.COMMENT_ATTR, new BasicCommentHandlerHC4()); - registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandlerHC4( - this.datepatterns)); - } - - /** Default constructor */ - public NetscapeDraftSpecHC4() { - this(null); - } - - /** - * Parses the Set-Cookie value into an array of Cookies. - * - *

    Syntax of the Set-Cookie HTTP Response Header:

    - * - *

    This is the format a CGI script would use to add to - * the HTTP headers a new piece of data which is to be stored by - * the client for later retrieval.

    - * - *
    -      *  Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure
    -      * 
    - * - *

    Please note that the Netscape draft specification does not fully conform to the HTTP - * header format. Comma character if present in Set-Cookie will not be treated - * as a header element separator

    - * - * @see - * The Cookie Spec. - * - * @param header the Set-Cookie received from the server - * @return an array of Cookies parsed from the Set-Cookie value - * @throws MalformedCookieException if an exception occurs during parsing - */ - public List parse(final Header header, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(header, "Header"); - Args.notNull(origin, "Cookie origin"); - if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE)) { - throw new MalformedCookieException("Unrecognized cookie header '" - + header.toString() + "'"); - } - final NetscapeDraftHeaderParserHC4 parser = NetscapeDraftHeaderParserHC4.DEFAULT; - final CharArrayBuffer buffer; - final ParserCursor cursor; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - cursor = new ParserCursor( - ((FormattedHeader) header).getValuePos(), - buffer.length()); - } else { - final String s = header.getValue(); - if (s == null) { - throw new MalformedCookieException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - cursor = new ParserCursor(0, buffer.length()); - } - return parse(new HeaderElement[] { parser.parseHeader(buffer, cursor) }, origin); - } - - public List
    formatCookies(final List cookies) { - Args.notEmpty(cookies, "List of cookies"); - final CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size()); - buffer.append(SM.COOKIE); - buffer.append(": "); - for (int i = 0; i < cookies.size(); i++) { - final Cookie cookie = cookies.get(i); - if (i > 0) { - buffer.append("; "); - } - buffer.append(cookie.getName()); - final String s = cookie.getValue(); - if (s != null) { - buffer.append("="); - buffer.append(s); - } - } - final List
    headers = new ArrayList
    (1); - headers.add(new BufferedHeader(buffer)); - return headers; - } - - public int getVersion() { - return 0; - } - - public Header getVersionHeader() { - return null; - } - - @Override - public String toString() { - return "netscape"; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/PublicSuffixFilterHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/PublicSuffixFilterHC4.java deleted file mode 100644 index 0727b8c5..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/PublicSuffixFilterHC4.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -import org.apache.http.client.utils.Punycode; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; - -/** - * Wraps a CookieAttributeHandler and leverages its match method - * to never match a suffix from a black list. May be used to provide - * additional security for cross-site attack types by preventing - * cookies from apparent domains that are not publicly available. - * An uptodate list of suffixes can be obtained from - * publicsuffix.org - * - * @since 4.0 - */ -public class PublicSuffixFilterHC4 implements CookieAttributeHandler { - private final CookieAttributeHandler wrapped; - private Set exceptions; - private Set suffixes; - - public PublicSuffixFilterHC4(final CookieAttributeHandler wrapped) { - this.wrapped = wrapped; - } - - /** - * Sets the suffix blacklist patterns. - * A pattern can be "com", "*.jp" - * TODO add support for patterns like "lib.*.us" - * @param suffixes - */ - public void setPublicSuffixes(final Collection suffixes) { - this.suffixes = new HashSet(suffixes); - } - - /** - * Sets the exceptions from the blacklist. Exceptions can not be patterns. - * TODO add support for patterns - * @param exceptions - */ - public void setExceptions(final Collection exceptions) { - this.exceptions = new HashSet(exceptions); - } - - /** - * Never matches if the cookie's domain is from the blacklist. - */ - public boolean match(final Cookie cookie, final CookieOrigin origin) { - if (isForPublicSuffix(cookie)) { - return false; - } - return wrapped.match(cookie, origin); - } - - public void parse(final SetCookie cookie, final String value) throws MalformedCookieException { - wrapped.parse(cookie, value); - } - - public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { - wrapped.validate(cookie, origin); - } - - private boolean isForPublicSuffix(final Cookie cookie) { - String domain = cookie.getDomain(); - if (domain.startsWith(".")) { - domain = domain.substring(1); - } - domain = Punycode.toUnicode(domain); - - // An exception rule takes priority over any other matching rule. - if (this.exceptions != null) { - if (this.exceptions.contains(domain)) { - return false; - } - } - - - if (this.suffixes == null) { - return false; - } - - do { - if (this.suffixes.contains(domain)) { - return true; - } - // patterns - if (domain.startsWith("*.")) { - domain = domain.substring(2); - } - final int nextdot = domain.indexOf('.'); - if (nextdot == -1) { - break; - } - domain = "*" + domain.substring(nextdot); - } while (domain.length() > 0); - - return false; - } -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/PublicSuffixListParserHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/PublicSuffixListParserHC4.java deleted file mode 100644 index 2f18ca40..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/PublicSuffixListParserHC4.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; -import java.util.ArrayList; -import java.util.Collection; - -import org.apache.http.annotation.Immutable; - -/** - * Parses the list from publicsuffix.org - * and configures a PublicSuffixFilterHC4. - * - * @since 4.0 - */ -@Immutable -public class PublicSuffixListParserHC4 { - private static final int MAX_LINE_LEN = 256; - private final PublicSuffixFilterHC4 filter; - - PublicSuffixListParserHC4(final PublicSuffixFilterHC4 filter) { - this.filter = filter; - } - - /** - * Parses the public suffix list format. - * When creating the reader from the file, make sure to - * use the correct encoding (the original list is in UTF-8). - * - * @param list the suffix list. The caller is responsible for closing the reader. - * @throws IOException on error while reading from list - */ - public void parse(final Reader list) throws IOException { - final Collection rules = new ArrayList(); - final Collection exceptions = new ArrayList(); - final BufferedReader r = new BufferedReader(list); - final StringBuilder sb = new StringBuilder(256); - boolean more = true; - while (more) { - more = readLine(r, sb); - String line = sb.toString(); - if (line.length() == 0) { - continue; - } - if (line.startsWith("//")) - { - continue; //entire lines can also be commented using // - } - if (line.startsWith(".")) - { - line = line.substring(1); // A leading dot is optional - } - // An exclamation mark (!) at the start of a rule marks an exception to a previous wildcard rule - final boolean isException = line.startsWith("!"); - if (isException) { - line = line.substring(1); - } - - if (isException) { - exceptions.add(line); - } else { - rules.add(line); - } - } - - filter.setPublicSuffixes(rules); - filter.setExceptions(exceptions); - } - - /** - * - * @param r - * @param sb - * @return false when the end of the stream is reached - * @throws IOException - */ - private boolean readLine(final Reader r, final StringBuilder sb) throws IOException { - sb.setLength(0); - int b; - boolean hitWhitespace = false; - while ((b = r.read()) != -1) { - final char c = (char) b; - if (c == '\n') { - break; - } - // Each line is only read up to the first whitespace - if (Character.isWhitespace(c)) { - hitWhitespace = true; - } - if (!hitWhitespace) { - sb.append(c); - } - if (sb.length() > MAX_LINE_LEN) - { - throw new IOException("Line too long"); // prevent excess memory usage - } - } - return (b != -1); - } -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2109DomainHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2109DomainHandlerHC4.java deleted file mode 100644 index 2208f1f7..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2109DomainHandlerHC4.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import java.util.Locale; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.CookieRestrictionViolationException; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; -import org.apache.http.util.Args; - -/** - * - * @since 4.0 - */ -@Immutable -public class RFC2109DomainHandlerHC4 implements CookieAttributeHandler { - - public RFC2109DomainHandlerHC4() { - super(); - } - - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (value == null) { - throw new MalformedCookieException("Missing value for domain attribute"); - } - if (value.trim().length() == 0) { - throw new MalformedCookieException("Blank value for domain attribute"); - } - cookie.setDomain(value); - } - - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - String host = origin.getHost(); - final String domain = cookie.getDomain(); - if (domain == null) { - throw new CookieRestrictionViolationException("Cookie domain may not be null"); - } - if (!domain.equals(host)) { - int dotIndex = domain.indexOf('.'); - if (dotIndex == -1) { - throw new CookieRestrictionViolationException("Domain attribute \"" - + domain - + "\" does not match the host \"" - + host + "\""); - } - // domain must start with dot - if (!domain.startsWith(".")) { - throw new CookieRestrictionViolationException("Domain attribute \"" - + domain - + "\" violates RFC 2109: domain must start with a dot"); - } - // domain must have at least one embedded dot - dotIndex = domain.indexOf('.', 1); - if (dotIndex < 0 || dotIndex == domain.length() - 1) { - throw new CookieRestrictionViolationException("Domain attribute \"" - + domain - + "\" violates RFC 2109: domain must contain an embedded dot"); - } - host = host.toLowerCase(Locale.ENGLISH); - if (!host.endsWith(domain)) { - throw new CookieRestrictionViolationException( - "Illegal domain attribute \"" + domain - + "\". Domain of origin: \"" + host + "\""); - } - // host minus domain may not contain any dots - final String hostWithoutDomain = host.substring(0, host.length() - domain.length()); - if (hostWithoutDomain.indexOf('.') != -1) { - throw new CookieRestrictionViolationException("Domain attribute \"" - + domain - + "\" violates RFC 2109: host minus domain may not contain any dots"); - } - } - } - - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - final String host = origin.getHost(); - final String domain = cookie.getDomain(); - if (domain == null) { - return false; - } - return host.equals(domain) || (domain.startsWith(".") && host.endsWith(domain)); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2109SpecFactoryHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2109SpecFactoryHC4.java deleted file mode 100644 index 533c1f4d..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2109SpecFactoryHC4.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.Collection; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.CookieSpec; -import org.apache.http.cookie.CookieSpecFactory; -import org.apache.http.cookie.CookieSpecProvider; -import org.apache.http.cookie.params.CookieSpecPNames; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HttpContext; - -/** - * {@link CookieSpecProvider} implementation that creates and initializes - * {@link RFC2109Spec} instances. - * - * @since 4.0 - */ -@Immutable -@SuppressWarnings("deprecation") -public class RFC2109SpecFactoryHC4 implements CookieSpecFactory, CookieSpecProvider { - - private final String[] datepatterns; - private final boolean oneHeader; - - public RFC2109SpecFactoryHC4(final String[] datepatterns, final boolean oneHeader) { - super(); - this.datepatterns = datepatterns; - this.oneHeader = oneHeader; - } - - public RFC2109SpecFactoryHC4() { - this(null, false); - } - - public CookieSpec newInstance(final HttpParams params) { - if (params != null) { - - String[] patterns = null; - final Collection param = (Collection) params.getParameter( - CookieSpecPNames.DATE_PATTERNS); - if (param != null) { - patterns = new String[param.size()]; - patterns = param.toArray(patterns); - } - final boolean singleHeader = params.getBooleanParameter( - CookieSpecPNames.SINGLE_COOKIE_HEADER, false); - - return new RFC2109SpecHC4(patterns, singleHeader); - } else { - return new RFC2109SpecHC4(); - } - } - - public CookieSpec create(final HttpContext context) { - return new RFC2109SpecHC4(this.datepatterns, this.oneHeader); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2109SpecHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2109SpecHC4.java deleted file mode 100644 index 88bd6f63..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2109SpecHC4.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.client.utils.DateUtils; -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.CookiePathComparator; -import org.apache.http.cookie.CookieRestrictionViolationException; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SM; -import org.apache.http.message.BufferedHeader; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * RFC 2109 compliant {@link org.apache.http.cookie.CookieSpec} implementation. - * This is an older version of the official HTTP state management specification - * superseded by RFC 2965. - * - * @see RFC2965SpecHC4 - * - * @since 4.0 - */ -@NotThreadSafe // superclass is @NotThreadSafe -public class RFC2109SpecHC4 extends CookieSpecBaseHC4 { - - private final static CookiePathComparator PATH_COMPARATOR = new CookiePathComparator(); - - private final static String[] DATE_PATTERNS = { - DateUtils.PATTERN_RFC1123, - DateUtils.PATTERN_RFC1036, - DateUtils.PATTERN_ASCTIME - }; - - private final String[] datepatterns; - private final boolean oneHeader; - - /** Default constructor */ - public RFC2109SpecHC4(final String[] datepatterns, final boolean oneHeader) { - super(); - if (datepatterns != null) { - this.datepatterns = datepatterns.clone(); - } else { - this.datepatterns = DATE_PATTERNS; - } - this.oneHeader = oneHeader; - registerAttribHandler(ClientCookie.VERSION_ATTR, new RFC2109VersionHandlerHC4()); - registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandlerHC4()); - registerAttribHandler(ClientCookie.DOMAIN_ATTR, new RFC2109DomainHandlerHC4()); - registerAttribHandler(ClientCookie.MAX_AGE_ATTR, new BasicMaxAgeHandlerHC4()); - registerAttribHandler(ClientCookie.SECURE_ATTR, new BasicSecureHandlerHC4()); - registerAttribHandler(ClientCookie.COMMENT_ATTR, new BasicCommentHandlerHC4()); - registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandlerHC4( - this.datepatterns)); - } - - /** Default constructor */ - public RFC2109SpecHC4() { - this(null, false); - } - - public List parse(final Header header, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(header, "Header"); - Args.notNull(origin, "Cookie origin"); - if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE)) { - throw new MalformedCookieException("Unrecognized cookie header '" - + header.toString() + "'"); - } - final HeaderElement[] elems = header.getElements(); - return parse(elems, origin); - } - - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - final String name = cookie.getName(); - if (name.indexOf(' ') != -1) { - throw new CookieRestrictionViolationException("Cookie name may not contain blanks"); - } - if (name.startsWith("$")) { - throw new CookieRestrictionViolationException("Cookie name may not start with $"); - } - super.validate(cookie, origin); - } - - public List
    formatCookies(final List cookies) { - Args.notEmpty(cookies, "List of cookies"); - List cookieList; - if (cookies.size() > 1) { - // Create a mutable copy and sort the copy. - cookieList = new ArrayList(cookies); - Collections.sort(cookieList, PATH_COMPARATOR); - } else { - cookieList = cookies; - } - if (this.oneHeader) { - return doFormatOneHeader(cookieList); - } else { - return doFormatManyHeaders(cookieList); - } - } - - private List
    doFormatOneHeader(final List cookies) { - int version = Integer.MAX_VALUE; - // Pick the lowest common denominator - for (final Cookie cookie : cookies) { - if (cookie.getVersion() < version) { - version = cookie.getVersion(); - } - } - final CharArrayBuffer buffer = new CharArrayBuffer(40 * cookies.size()); - buffer.append(SM.COOKIE); - buffer.append(": "); - buffer.append("$Version="); - buffer.append(Integer.toString(version)); - for (final Cookie cooky : cookies) { - buffer.append("; "); - final Cookie cookie = cooky; - formatCookieAsVer(buffer, cookie, version); - } - final List
    headers = new ArrayList
    (1); - headers.add(new BufferedHeader(buffer)); - return headers; - } - - private List
    doFormatManyHeaders(final List cookies) { - final List
    headers = new ArrayList
    (cookies.size()); - for (final Cookie cookie : cookies) { - final int version = cookie.getVersion(); - final CharArrayBuffer buffer = new CharArrayBuffer(40); - buffer.append("Cookie: "); - buffer.append("$Version="); - buffer.append(Integer.toString(version)); - buffer.append("; "); - formatCookieAsVer(buffer, cookie, version); - headers.add(new BufferedHeader(buffer)); - } - return headers; - } - - /** - * Return a name/value string suitable for sending in a "Cookie" - * header as defined in RFC 2109 for backward compatibility with cookie - * version 0 - * @param buffer The char array buffer to use for output - * @param name The cookie name - * @param value The cookie value - * @param version The cookie version - */ - protected void formatParamAsVer(final CharArrayBuffer buffer, - final String name, final String value, final int version) { - buffer.append(name); - buffer.append("="); - if (value != null) { - if (version > 0) { - buffer.append('\"'); - buffer.append(value); - buffer.append('\"'); - } else { - buffer.append(value); - } - } - } - - /** - * Return a string suitable for sending in a "Cookie" header - * as defined in RFC 2109 for backward compatibility with cookie version 0 - * @param buffer The char array buffer to use for output - * @param cookie The {@link Cookie} to be formatted as string - * @param version The version to use. - */ - protected void formatCookieAsVer(final CharArrayBuffer buffer, - final Cookie cookie, final int version) { - formatParamAsVer(buffer, cookie.getName(), cookie.getValue(), version); - if (cookie.getPath() != null) { - if (cookie instanceof ClientCookie - && ((ClientCookie) cookie).containsAttribute(ClientCookie.PATH_ATTR)) { - buffer.append("; "); - formatParamAsVer(buffer, "$Path", cookie.getPath(), version); - } - } - if (cookie.getDomain() != null) { - if (cookie instanceof ClientCookie - && ((ClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR)) { - buffer.append("; "); - formatParamAsVer(buffer, "$Domain", cookie.getDomain(), version); - } - } - } - - public int getVersion() { - return 1; - } - - public Header getVersionHeader() { - return null; - } - - @Override - public String toString() { - return "rfc2109"; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2109VersionHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2109VersionHandlerHC4.java deleted file mode 100644 index 23456b03..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2109VersionHandlerHC4.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.CookieRestrictionViolationException; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; -import org.apache.http.util.Args; - -/** - * - * @since 4.0 - */ -@Immutable -public class RFC2109VersionHandlerHC4 extends AbstractCookieAttributeHandlerHC4 { - - public RFC2109VersionHandlerHC4() { - super(); - } - - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (value == null) { - throw new MalformedCookieException("Missing value for version attribute"); - } - if (value.trim().length() == 0) { - throw new MalformedCookieException("Blank value for version attribute"); - } - try { - cookie.setVersion(Integer.parseInt(value)); - } catch (final NumberFormatException e) { - throw new MalformedCookieException("Invalid version: " - + e.getMessage()); - } - } - - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (cookie.getVersion() < 0) { - throw new CookieRestrictionViolationException("Cookie version may not be negative"); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965CommentUrlAttributeHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965CommentUrlAttributeHandlerHC4.java deleted file mode 100644 index 7a94ac0d..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965CommentUrlAttributeHandlerHC4.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; -import org.apache.http.cookie.SetCookie2; - -/** - * "CommentURL" cookie attribute handler for RFC 2965 cookie spec. - * - * @since 4.0 - */ -@Immutable -public class RFC2965CommentUrlAttributeHandlerHC4 implements CookieAttributeHandler { - - public RFC2965CommentUrlAttributeHandlerHC4() { - super(); - } - - public void parse(final SetCookie cookie, final String commenturl) - throws MalformedCookieException { - if (cookie instanceof SetCookie2) { - final SetCookie2 cookie2 = (SetCookie2) cookie; - cookie2.setCommentURL(commenturl); - } - } - - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - } - - public boolean match(final Cookie cookie, final CookieOrigin origin) { - return true; - } - - } diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965DiscardAttributeHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965DiscardAttributeHandlerHC4.java deleted file mode 100644 index 859708e8..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965DiscardAttributeHandlerHC4.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; -import org.apache.http.cookie.SetCookie2; - -/** - * "Discard" cookie attribute handler for RFC 2965 cookie spec. - * - * @since 4.0 - */ -@Immutable -public class RFC2965DiscardAttributeHandlerHC4 implements CookieAttributeHandler { - - public RFC2965DiscardAttributeHandlerHC4() { - super(); - } - - public void parse(final SetCookie cookie, final String commenturl) - throws MalformedCookieException { - if (cookie instanceof SetCookie2) { - final SetCookie2 cookie2 = (SetCookie2) cookie; - cookie2.setDiscard(true); - } - } - - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - } - - public boolean match(final Cookie cookie, final CookieOrigin origin) { - return true; - } - - } diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965DomainAttributeHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965DomainAttributeHandlerHC4.java deleted file mode 100644 index fd0aa1cb..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965DomainAttributeHandlerHC4.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.Locale; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.CookieRestrictionViolationException; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; -import org.apache.http.util.Args; - -/** - * "Domain" cookie attribute handler for RFC 2965 cookie spec. - * - * - * @since 3.1 - */ -@Immutable -public class RFC2965DomainAttributeHandlerHC4 implements CookieAttributeHandler { - - public RFC2965DomainAttributeHandlerHC4() { - super(); - } - - /** - * Parse cookie domain attribute. - */ - public void parse( - final SetCookie cookie, final String domain) throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (domain == null) { - throw new MalformedCookieException( - "Missing value for domain attribute"); - } - if (domain.trim().length() == 0) { - throw new MalformedCookieException( - "Blank value for domain attribute"); - } - String s = domain; - s = s.toLowerCase(Locale.ENGLISH); - if (!domain.startsWith(".")) { - // Per RFC 2965 section 3.2.2 - // "... If an explicitly specified value does not start with - // a dot, the user agent supplies a leading dot ..." - // That effectively implies that the domain attribute - // MAY NOT be an IP address of a host name - s = '.' + s; - } - cookie.setDomain(s); - } - - /** - * Performs domain-match as defined by the RFC2965. - *

    - * Host A's name domain-matches host B's if - *

      - *
        their host name strings string-compare equal; or
      - *
        A is a HDN string and has the form NB, where N is a non-empty - * name string, B has the form .B', and B' is a HDN string. (So, - * x.y.com domain-matches .Y.com but not Y.com.)
      - *
    - * - * @param host host name where cookie is received from or being sent to. - * @param domain The cookie domain attribute. - * @return true if the specified host matches the given domain. - */ - public boolean domainMatch(final String host, final String domain) { - final boolean match = host.equals(domain) - || (domain.startsWith(".") && host.endsWith(domain)); - - return match; - } - - /** - * Validate cookie domain attribute. - */ - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - final String host = origin.getHost().toLowerCase(Locale.ENGLISH); - if (cookie.getDomain() == null) { - throw new CookieRestrictionViolationException("Invalid cookie state: " + - "domain not specified"); - } - final String cookieDomain = cookie.getDomain().toLowerCase(Locale.ENGLISH); - - if (cookie instanceof ClientCookie - && ((ClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR)) { - // Domain attribute must start with a dot - if (!cookieDomain.startsWith(".")) { - throw new CookieRestrictionViolationException("Domain attribute \"" + - cookie.getDomain() + "\" violates RFC 2109: domain must start with a dot"); - } - - // Domain attribute must contain at least one embedded dot, - // or the value must be equal to .local. - final int dotIndex = cookieDomain.indexOf('.', 1); - if (((dotIndex < 0) || (dotIndex == cookieDomain.length() - 1)) - && (!cookieDomain.equals(".local"))) { - throw new CookieRestrictionViolationException( - "Domain attribute \"" + cookie.getDomain() - + "\" violates RFC 2965: the value contains no embedded dots " - + "and the value is not .local"); - } - - // The effective host name must domain-match domain attribute. - if (!domainMatch(host, cookieDomain)) { - throw new CookieRestrictionViolationException( - "Domain attribute \"" + cookie.getDomain() - + "\" violates RFC 2965: effective host name does not " - + "domain-match domain attribute."); - } - - // effective host name minus domain must not contain any dots - final String effectiveHostWithoutDomain = host.substring( - 0, host.length() - cookieDomain.length()); - if (effectiveHostWithoutDomain.indexOf('.') != -1) { - throw new CookieRestrictionViolationException("Domain attribute \"" - + cookie.getDomain() + "\" violates RFC 2965: " - + "effective host minus domain may not contain any dots"); - } - } else { - // Domain was not specified in header. In this case, domain must - // string match request host (case-insensitive). - if (!cookie.getDomain().equals(host)) { - throw new CookieRestrictionViolationException("Illegal domain attribute: \"" - + cookie.getDomain() + "\"." - + "Domain of origin: \"" - + host + "\""); - } - } - } - - /** - * Match cookie domain attribute. - */ - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - final String host = origin.getHost().toLowerCase(Locale.ENGLISH); - final String cookieDomain = cookie.getDomain(); - - // The effective host name MUST domain-match the Domain - // attribute of the cookie. - if (!domainMatch(host, cookieDomain)) { - return false; - } - // effective host name minus domain must not contain any dots - final String effectiveHostWithoutDomain = host.substring( - 0, host.length() - cookieDomain.length()); - return effectiveHostWithoutDomain.indexOf('.') == -1; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965PortAttributeHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965PortAttributeHandlerHC4.java deleted file mode 100644 index cf8acf93..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965PortAttributeHandlerHC4.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.StringTokenizer; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.CookieRestrictionViolationException; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; -import org.apache.http.cookie.SetCookie2; -import org.apache.http.util.Args; - -/** - * "Port" cookie attribute handler for RFC 2965 cookie spec. - * - * @since 4.0 - */ -@Immutable -public class RFC2965PortAttributeHandlerHC4 implements CookieAttributeHandler { - - public RFC2965PortAttributeHandlerHC4() { - super(); - } - - /** - * Parses the given Port attribute value (e.g. "8000,8001,8002") - * into an array of ports. - * - * @param portValue port attribute value - * @return parsed array of ports - * @throws MalformedCookieException if there is a problem in - * parsing due to invalid portValue. - */ - private static int[] parsePortAttribute(final String portValue) - throws MalformedCookieException { - final StringTokenizer st = new StringTokenizer(portValue, ","); - final int[] ports = new int[st.countTokens()]; - try { - int i = 0; - while(st.hasMoreTokens()) { - ports[i] = Integer.parseInt(st.nextToken().trim()); - if (ports[i] < 0) { - throw new MalformedCookieException ("Invalid Port attribute."); - } - ++i; - } - } catch (final NumberFormatException e) { - throw new MalformedCookieException ("Invalid Port " - + "attribute: " + e.getMessage()); - } - return ports; - } - - /** - * Returns true if the given port exists in the given - * ports list. - * - * @param port port of host where cookie was received from or being sent to. - * @param ports port list - * @return true returns true if the given port exists in - * the given ports list; false otherwise. - */ - private static boolean portMatch(final int port, final int[] ports) { - boolean portInList = false; - for (final int port2 : ports) { - if (port == port2) { - portInList = true; - break; - } - } - return portInList; - } - - /** - * Parse cookie port attribute. - */ - public void parse(final SetCookie cookie, final String portValue) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (cookie instanceof SetCookie2) { - final SetCookie2 cookie2 = (SetCookie2) cookie; - if (portValue != null && portValue.trim().length() > 0) { - final int[] ports = parsePortAttribute(portValue); - cookie2.setPorts(ports); - } - } - } - - /** - * Validate cookie port attribute. If the Port attribute was specified - * in header, the request port must be in cookie's port list. - */ - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - final int port = origin.getPort(); - if (cookie instanceof ClientCookie - && ((ClientCookie) cookie).containsAttribute(ClientCookie.PORT_ATTR)) { - if (!portMatch(port, cookie.getPorts())) { - throw new CookieRestrictionViolationException( - "Port attribute violates RFC 2965: " - + "Request port not found in cookie's port list."); - } - } - } - - /** - * Match cookie port attribute. If the Port attribute is not specified - * in header, the cookie can be sent to any port. Otherwise, the request port - * must be in the cookie's port list. - */ - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - final int port = origin.getPort(); - if (cookie instanceof ClientCookie - && ((ClientCookie) cookie).containsAttribute(ClientCookie.PORT_ATTR)) { - if (cookie.getPorts() == null) { - // Invalid cookie state: port not specified - return false; - } - if (!portMatch(port, cookie.getPorts())) { - return false; - } - } - return true; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965SpecFactoryHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965SpecFactoryHC4.java deleted file mode 100644 index 2c0a95c7..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965SpecFactoryHC4.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.Collection; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.CookieSpec; -import org.apache.http.cookie.CookieSpecFactory; -import org.apache.http.cookie.CookieSpecProvider; -import org.apache.http.cookie.params.CookieSpecPNames; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HttpContext; - -/** - * {@link CookieSpecProvider} implementation that creates and initializes - * {@link RFC2965Spec} instances. - * - * @since 4.0 - */ -@Immutable -@SuppressWarnings("deprecation") -public class RFC2965SpecFactoryHC4 implements CookieSpecFactory, CookieSpecProvider { - - private final String[] datepatterns; - private final boolean oneHeader; - - public RFC2965SpecFactoryHC4(final String[] datepatterns, final boolean oneHeader) { - super(); - this.datepatterns = datepatterns; - this.oneHeader = oneHeader; - } - - public RFC2965SpecFactoryHC4() { - this(null, false); - } - - public CookieSpec newInstance(final HttpParams params) { - if (params != null) { - - String[] patterns = null; - final Collection param = (Collection) params.getParameter( - CookieSpecPNames.DATE_PATTERNS); - if (param != null) { - patterns = new String[param.size()]; - patterns = param.toArray(patterns); - } - final boolean singleHeader = params.getBooleanParameter( - CookieSpecPNames.SINGLE_COOKIE_HEADER, false); - - return new RFC2965SpecHC4(patterns, singleHeader); - } else { - return new RFC2965SpecHC4(); - } - } - - public CookieSpec create(final HttpContext context) { - return new RFC2965SpecHC4(this.datepatterns, this.oneHeader); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965SpecHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965SpecHC4.java deleted file mode 100644 index 89992b5e..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965SpecHC4.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.NameValuePair; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SM; -import org.apache.http.message.BufferedHeader; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * RFC 2965 compliant {@link org.apache.http.cookie.CookieSpec} implementation. - * - * @since 4.0 - */ -@NotThreadSafe // superclass is @NotThreadSafe -public class RFC2965SpecHC4 extends RFC2109SpecHC4 { - - /** - * Default constructor - * - */ - public RFC2965SpecHC4() { - this(null, false); - } - - public RFC2965SpecHC4(final String[] datepatterns, final boolean oneHeader) { - super(datepatterns, oneHeader); - registerAttribHandler(ClientCookie.DOMAIN_ATTR, new RFC2965DomainAttributeHandlerHC4()); - registerAttribHandler(ClientCookie.PORT_ATTR, new RFC2965PortAttributeHandlerHC4()); - registerAttribHandler(ClientCookie.COMMENTURL_ATTR, new RFC2965CommentUrlAttributeHandlerHC4()); - registerAttribHandler(ClientCookie.DISCARD_ATTR, new RFC2965DiscardAttributeHandlerHC4()); - registerAttribHandler(ClientCookie.VERSION_ATTR, new RFC2965VersionAttributeHandlerHC4()); - } - - @Override - public List parse( - final Header header, - final CookieOrigin origin) throws MalformedCookieException { - Args.notNull(header, "Header"); - Args.notNull(origin, "Cookie origin"); - if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE2)) { - throw new MalformedCookieException("Unrecognized cookie header '" - + header.toString() + "'"); - } - final HeaderElement[] elems = header.getElements(); - return createCookies(elems, adjustEffectiveHost(origin)); - } - - @Override - protected List parse( - final HeaderElement[] elems, - final CookieOrigin origin) throws MalformedCookieException { - return createCookies(elems, adjustEffectiveHost(origin)); - } - - private List createCookies( - final HeaderElement[] elems, - final CookieOrigin origin) throws MalformedCookieException { - final List cookies = new ArrayList(elems.length); - for (final HeaderElement headerelement : elems) { - final String name = headerelement.getName(); - final String value = headerelement.getValue(); - if (name == null || name.length() == 0) { - throw new MalformedCookieException("Cookie name may not be empty"); - } - - final BasicClientCookie2HC4 cookie = new BasicClientCookie2HC4(name, value); - cookie.setPath(getDefaultPath(origin)); - cookie.setDomain(getDefaultDomain(origin)); - cookie.setPorts(new int [] { origin.getPort() }); - // cycle through the parameters - final NameValuePair[] attribs = headerelement.getParameters(); - - // Eliminate duplicate attributes. The first occurrence takes precedence - // See RFC2965: 3.2 Origin Server Role - final Map attribmap = - new HashMap(attribs.length); - for (int j = attribs.length - 1; j >= 0; j--) { - final NameValuePair param = attribs[j]; - attribmap.put(param.getName().toLowerCase(Locale.ENGLISH), param); - } - for (final Map.Entry entry : attribmap.entrySet()) { - final NameValuePair attrib = entry.getValue(); - final String s = attrib.getName().toLowerCase(Locale.ENGLISH); - - cookie.setAttribute(s, attrib.getValue()); - - final CookieAttributeHandler handler = findAttribHandler(s); - if (handler != null) { - handler.parse(cookie, attrib.getValue()); - } - } - cookies.add(cookie); - } - return cookies; - } - - @Override - public void validate( - final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - super.validate(cookie, adjustEffectiveHost(origin)); - } - - @Override - public boolean match(final Cookie cookie, final CookieOrigin origin) { - Args.notNull(cookie, "Cookie"); - Args.notNull(origin, "Cookie origin"); - return super.match(cookie, adjustEffectiveHost(origin)); - } - - /** - * Adds valid Port attribute value, e.g. "8000,8001,8002" - */ - @Override - protected void formatCookieAsVer(final CharArrayBuffer buffer, - final Cookie cookie, final int version) { - super.formatCookieAsVer(buffer, cookie, version); - // format port attribute - if (cookie instanceof ClientCookie) { - // Test if the port attribute as set by the origin server is not blank - final String s = ((ClientCookie) cookie).getAttribute(ClientCookie.PORT_ATTR); - if (s != null) { - buffer.append("; $Port"); - buffer.append("=\""); - if (s.trim().length() > 0) { - final int[] ports = cookie.getPorts(); - if (ports != null) { - final int len = ports.length; - for (int i = 0; i < len; i++) { - if (i > 0) { - buffer.append(","); - } - buffer.append(Integer.toString(ports[i])); - } - } - } - buffer.append("\""); - } - } - } - - /** - * Set 'effective host name' as defined in RFC 2965. - *

    - * If a host name contains no dots, the effective host name is - * that name with the string .local appended to it. Otherwise - * the effective host name is the same as the host name. Note - * that all effective host names contain at least one dot. - * - * @param origin origin where cookie is received from or being sent to. - */ - private static CookieOrigin adjustEffectiveHost(final CookieOrigin origin) { - String host = origin.getHost(); - - // Test if the host name appears to be a fully qualified DNS name, - // IPv4 address or IPv6 address - boolean isLocalHost = true; - for (int i = 0; i < host.length(); i++) { - final char ch = host.charAt(i); - if (ch == '.' || ch == ':') { - isLocalHost = false; - break; - } - } - if (isLocalHost) { - host += ".local"; - return new CookieOrigin( - host, - origin.getPort(), - origin.getPath(), - origin.isSecure()); - } else { - return origin; - } - } - - @Override - public int getVersion() { - return 1; - } - - @Override - public Header getVersionHeader() { - final CharArrayBuffer buffer = new CharArrayBuffer(40); - buffer.append(SM.COOKIE2); - buffer.append(": "); - buffer.append("$Version="); - buffer.append(Integer.toString(getVersion())); - return new BufferedHeader(buffer); - } - - @Override - public String toString() { - return "rfc2965"; - } - -} - diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965VersionAttributeHandlerHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965VersionAttributeHandlerHC4.java deleted file mode 100644 index 2115ac1f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/RFC2965VersionAttributeHandlerHC4.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import org.apache.http.annotation.Immutable; -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.CookieRestrictionViolationException; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; -import org.apache.http.cookie.SetCookie2; -import org.apache.http.util.Args; - -/** - * "Version" cookie attribute handler for RFC 2965 cookie spec. - * - * @since 4.0 - */ -@Immutable -public class RFC2965VersionAttributeHandlerHC4 implements CookieAttributeHandler { - - public RFC2965VersionAttributeHandlerHC4() { - super(); - } - - /** - * Parse cookie version attribute. - */ - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (value == null) { - throw new MalformedCookieException( - "Missing value for version attribute"); - } - int version = -1; - try { - version = Integer.parseInt(value); - } catch (final NumberFormatException e) { - version = -1; - } - if (version < 0) { - throw new MalformedCookieException("Invalid cookie version."); - } - cookie.setVersion(version); - } - - /** - * validate cookie version attribute. Version attribute is REQUIRED. - */ - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - Args.notNull(cookie, "Cookie"); - if (cookie instanceof SetCookie2) { - if (cookie instanceof ClientCookie - && !((ClientCookie) cookie).containsAttribute(ClientCookie.VERSION_ATTR)) { - throw new CookieRestrictionViolationException( - "Violates RFC 2965. Version attribute is required."); - } - } - } - - public boolean match(final Cookie cookie, final CookieOrigin origin) { - return true; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/package-info.java deleted file mode 100644 index 632b850c..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/cookie/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Default implementations of standard and common HTTP state - * management policies. - */ -package org.apache.http.impl.cookie; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/entity/DisallowIdentityContentLengthStrategy.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/entity/DisallowIdentityContentLengthStrategy.java deleted file mode 100644 index 9af65a6f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/entity/DisallowIdentityContentLengthStrategy.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.entity; - -import org.apache.http.HttpException; -import org.apache.http.HttpMessage; -import org.apache.http.ProtocolException; -import org.apache.http.annotation.Immutable; -import org.apache.http.entity.ContentLengthStrategy; - -/** - * Decorator for {@link ContentLengthStrategy} implementations that disallows the use of - * identity transfer encoding. - * - * @since 4.2 - */ -@Immutable -public class DisallowIdentityContentLengthStrategy implements ContentLengthStrategy { - - public static final DisallowIdentityContentLengthStrategy INSTANCE = - new DisallowIdentityContentLengthStrategy(new LaxContentLengthStrategyHC4(0)); - - private final ContentLengthStrategy contentLengthStrategy; - - public DisallowIdentityContentLengthStrategy(final ContentLengthStrategy contentLengthStrategy) { - super(); - this.contentLengthStrategy = contentLengthStrategy; - } - - public long determineLength(final HttpMessage message) throws HttpException { - final long result = this.contentLengthStrategy.determineLength(message); - if (result == ContentLengthStrategy.IDENTITY) { - throw new ProtocolException("Identity transfer encoding cannot be used"); - } - return result; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/entity/LaxContentLengthStrategyHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/entity/LaxContentLengthStrategyHC4.java deleted file mode 100644 index fd8dcab4..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/entity/LaxContentLengthStrategyHC4.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.entity; - -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.HttpException; -import org.apache.http.HttpMessage; -import org.apache.http.ParseException; -import org.apache.http.ProtocolException; -import org.apache.http.annotation.Immutable; -import org.apache.http.entity.ContentLengthStrategy; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.Args; - -/** - * The lax implementation of the content length strategy. This class will ignore - * unrecognized transfer encodings and malformed Content-Length - * header values. - *

    - * This class recognizes "chunked" and "identitiy" transfer-coding only. - * - * @since 4.0 - */ -@Immutable -public class LaxContentLengthStrategyHC4 implements ContentLengthStrategy { - - public static final LaxContentLengthStrategyHC4 INSTANCE = new LaxContentLengthStrategyHC4(); - - private final int implicitLen; - - /** - * Creates LaxContentLengthStrategy instance with the given length used per default - * when content length is not explicitly specified in the message. - * - * @param implicitLen implicit content length. - * - * @since 4.2 - */ - public LaxContentLengthStrategyHC4(final int implicitLen) { - super(); - this.implicitLen = implicitLen; - } - - /** - * Creates LaxContentLengthStrategy instance. {@link ContentLengthStrategy#IDENTITY} - * is used per default when content length is not explicitly specified in the message. - */ - public LaxContentLengthStrategyHC4() { - this(IDENTITY); - } - - public long determineLength(final HttpMessage message) throws HttpException { - Args.notNull(message, "HTTP message"); - - final Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING); - // We use Transfer-Encoding if present and ignore Content-Length. - // RFC2616, 4.4 item number 3 - if (transferEncodingHeader != null) { - final HeaderElement[] encodings; - try { - encodings = transferEncodingHeader.getElements(); - } catch (final ParseException px) { - throw new ProtocolException - ("Invalid Transfer-Encoding header value: " + - transferEncodingHeader, px); - } - // The chunked encoding must be the last one applied RFC2616, 14.41 - final int len = encodings.length; - if (HTTP.IDENTITY_CODING.equalsIgnoreCase(transferEncodingHeader.getValue())) { - return IDENTITY; - } else if ((len > 0) && (HTTP.CHUNK_CODING.equalsIgnoreCase( - encodings[len - 1].getName()))) { - return CHUNKED; - } else { - return IDENTITY; - } - } - final Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN); - if (contentLengthHeader != null) { - long contentlen = -1; - final Header[] headers = message.getHeaders(HTTP.CONTENT_LEN); - for (int i = headers.length - 1; i >= 0; i--) { - final Header header = headers[i]; - try { - contentlen = Long.parseLong(header.getValue()); - break; - } catch (final NumberFormatException ignore) { - } - // See if we can have better luck with another header, if present - } - if (contentlen >= 0) { - return contentlen; - } else { - return IDENTITY; - } - } - return this.implicitLen; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/entity/StrictContentLengthStrategyHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/entity/StrictContentLengthStrategyHC4.java deleted file mode 100644 index 41b0f367..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/entity/StrictContentLengthStrategyHC4.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.entity; - -import org.apache.http.Header; -import org.apache.http.HttpException; -import org.apache.http.HttpMessage; -import org.apache.http.HttpVersion; -import org.apache.http.ProtocolException; -import org.apache.http.annotation.Immutable; -import org.apache.http.entity.ContentLengthStrategy; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.Args; - -/** - * The strict implementation of the content length strategy. This class - * will throw {@link ProtocolException} if it encounters an unsupported - * transfer encoding or a malformed Content-Length header - * value. - *

    - * This class recognizes "chunked" and "identitiy" transfer-coding only. - * - * @since 4.0 - */ -@Immutable -public class StrictContentLengthStrategyHC4 implements ContentLengthStrategy { - - public static final StrictContentLengthStrategyHC4 INSTANCE = new StrictContentLengthStrategyHC4(); - - private final int implicitLen; - - /** - * Creates StrictContentLengthStrategy instance with the given length used per default - * when content length is not explicitly specified in the message. - * - * @param implicitLen implicit content length. - * - * @since 4.2 - */ - public StrictContentLengthStrategyHC4(final int implicitLen) { - super(); - this.implicitLen = implicitLen; - } - - /** - * Creates StrictContentLengthStrategy instance. {@link ContentLengthStrategy#IDENTITY} - * is used per default when content length is not explicitly specified in the message. - */ - public StrictContentLengthStrategyHC4() { - this(IDENTITY); - } - - public long determineLength(final HttpMessage message) throws HttpException { - Args.notNull(message, "HTTP message"); - // Although Transfer-Encoding is specified as a list, in practice - // it is either missing or has the single value "chunked". So we - // treat it as a single-valued header here. - final Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING); - if (transferEncodingHeader != null) { - final String s = transferEncodingHeader.getValue(); - if (HTTP.CHUNK_CODING.equalsIgnoreCase(s)) { - if (message.getProtocolVersion().lessEquals(HttpVersion.HTTP_1_0)) { - throw new ProtocolException( - "Chunked transfer encoding not allowed for " + - message.getProtocolVersion()); - } - return CHUNKED; - } else if (HTTP.IDENTITY_CODING.equalsIgnoreCase(s)) { - return IDENTITY; - } else { - throw new ProtocolException( - "Unsupported transfer encoding: " + s); - } - } - final Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN); - if (contentLengthHeader != null) { - final String s = contentLengthHeader.getValue(); - try { - final long len = Long.parseLong(s); - if (len < 0) { - throw new ProtocolException("Negative content length: " + s); - } - return len; - } catch (final NumberFormatException e) { - throw new ProtocolException("Invalid content length: " + s); - } - } - return this.implicitLen; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/entity/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/entity/package-info.java deleted file mode 100644 index 98b63127..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/entity/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Default implementations of entity content strategies. - */ -package org.apache.http.impl.entity; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/BackoffStrategyExec.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/BackoffStrategyExec.java deleted file mode 100644 index 0cd9433e..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/BackoffStrategyExec.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.execchain; - -import java.io.IOException; -import java.lang.reflect.UndeclaredThrowableException; - -import org.apache.http.HttpException; -import org.apache.http.annotation.Immutable; -import org.apache.http.client.BackoffManager; -import org.apache.http.client.ConnectionBackoffStrategy; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpExecutionAware; -import org.apache.http.client.methods.HttpRequestWrapper; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.util.Args; - -/** - * @since 4.3 - */ -@Immutable -public class BackoffStrategyExec implements ClientExecChain { - - private final ClientExecChain requestExecutor; - private final ConnectionBackoffStrategy connectionBackoffStrategy; - private final BackoffManager backoffManager; - - public BackoffStrategyExec( - final ClientExecChain requestExecutor, - final ConnectionBackoffStrategy connectionBackoffStrategy, - final BackoffManager backoffManager) { - super(); - Args.notNull(requestExecutor, "HTTP client request executor"); - Args.notNull(connectionBackoffStrategy, "Connection backoff strategy"); - Args.notNull(backoffManager, "Backoff manager"); - this.requestExecutor = requestExecutor; - this.connectionBackoffStrategy = connectionBackoffStrategy; - this.backoffManager = backoffManager; - } - - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, - final HttpClientContext context, - final HttpExecutionAware execAware) throws IOException, HttpException { - Args.notNull(route, "HTTP route"); - Args.notNull(request, "HTTP request"); - Args.notNull(context, "HTTP context"); - CloseableHttpResponse out = null; - try { - out = this.requestExecutor.execute(route, request, context, execAware); - } catch (final Exception ex) { - if (out != null) { - out.close(); - } - if (this.connectionBackoffStrategy.shouldBackoff(ex)) { - this.backoffManager.backOff(route); - } - if (ex instanceof RuntimeException) { - throw (RuntimeException) ex; - } - if (ex instanceof HttpException) { - throw (HttpException) ex; - } - if (ex instanceof IOException) { - throw (IOException) ex; - } - throw new UndeclaredThrowableException(ex); - } - if (this.connectionBackoffStrategy.shouldBackoff(out)) { - this.backoffManager.backOff(route); - } else { - this.backoffManager.probe(route); - } - return out; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/ClientExecChain.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/ClientExecChain.java deleted file mode 100644 index 2b03e293..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/ClientExecChain.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.execchain; - -import java.io.IOException; - -import org.apache.http.HttpException; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpExecutionAware; -import org.apache.http.client.methods.HttpRequestWrapper; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.conn.routing.HttpRoute; - -/** - * This interface represents an element in the HTTP request execution chain. Each element can - * either be a decorator around another element that implements a cross cutting aspect or - * a self-contained executor capable of producing a response for the given request. - *

    - * Important: please note it is required for decorators that implement post execution aspects - * or response post-processing of any sort to release resources associated with the response - * by calling {@link CloseableHttpResponse#close()} methods in case of an I/O, protocol or - * runtime exception, or in case the response is not propagated to the caller. - * - * @since 4.3 - */ -public interface ClientExecChain { - - /** - * Executes th request either by transmitting it to the target server or - * by passing it onto the next executor in the request execution chain. - * - * @param route connection route. - * @param request current request. - * @param clientContext current HTTP context. - * @param execAware receiver of notifications of blocking I/O operations. - * @return HTTP response either received from the opposite endpoint - * or generated locally. - * @throws IOException in case of a I/O error. - * (this type of exceptions are potentially recoverable). - * @throws HttpException in case of an HTTP protocol error - * (usually this type of exceptions are non-recoverable). - */ - CloseableHttpResponse execute( - HttpRoute route, - HttpRequestWrapper request, - HttpClientContext clientContext, - HttpExecutionAware execAware) throws IOException, HttpException; - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/ConnectionHolder.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/ConnectionHolder.java deleted file mode 100644 index ff5aef05..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/ConnectionHolder.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.execchain; - -import java.io.Closeable; -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -import android.util.Log; -import org.apache.http.HttpClientConnection; -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.concurrent.Cancellable; -import org.apache.http.conn.ConnectionReleaseTrigger; -import org.apache.http.conn.HttpClientConnectionManager; - -/** - * Internal connection holder. - * - * @since 4.3 - */ -@ThreadSafe -class ConnectionHolder implements ConnectionReleaseTrigger, Cancellable, Closeable { - - private final static String TAG = "HttpClient"; - - private final HttpClientConnectionManager manager; - private final HttpClientConnection managedConn; - private volatile boolean reusable; - private volatile Object state; - private volatile long validDuration; - private volatile TimeUnit tunit; - - private volatile boolean released; - - public ConnectionHolder( - final HttpClientConnectionManager manager, - final HttpClientConnection managedConn) { - super(); - this.manager = manager; - this.managedConn = managedConn; - } - - public boolean isReusable() { - return this.reusable; - } - - public void markReusable() { - this.reusable = true; - } - - public void markNonReusable() { - this.reusable = false; - } - - public void setState(final Object state) { - this.state = state; - } - - public void setValidFor(final long duration, final TimeUnit tunit) { - synchronized (this.managedConn) { - this.validDuration = duration; - this.tunit = tunit; - } - } - - public void releaseConnection() { - synchronized (this.managedConn) { - if (this.released) { - return; - } - this.released = true; - if (this.reusable) { - this.manager.releaseConnection(this.managedConn, - this.state, this.validDuration, this.tunit); - } else { - try { - this.managedConn.close(); - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Connection discarded"); - } - } catch (final IOException ex) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, ex.getMessage(), ex); - } - } finally { - this.manager.releaseConnection( - this.managedConn, null, 0, TimeUnit.MILLISECONDS); - } - } - } - } - - public void abortConnection() { - synchronized (this.managedConn) { - if (this.released) { - return; - } - this.released = true; - try { - this.managedConn.shutdown(); - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Connection discarded"); - } - } catch (final IOException ex) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, ex.getMessage(), ex); - } - } finally { - this.manager.releaseConnection( - this.managedConn, null, 0, TimeUnit.MILLISECONDS); - } - } - } - - public boolean cancel() { - final boolean alreadyReleased = this.released; - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Cancelling request execution"); - } - abortConnection(); - return !alreadyReleased; - } - - public boolean isReleased() { - return this.released; - } - - public void close() throws IOException { - abortConnection(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/HttpResponseProxy.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/HttpResponseProxy.java deleted file mode 100644 index 413bf0e2..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/HttpResponseProxy.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.execchain; - -import java.io.IOException; -import java.util.Locale; - -import org.apache.http.Header; -import org.apache.http.HeaderIterator; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.ProtocolVersion; -import org.apache.http.StatusLine; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.params.HttpParams; - -/** - * A proxy class for {@link org.apache.http.HttpResponse} that can be used to release client connection - * associated with the original response. - * - * @since 4.3 - */ -@NotThreadSafe -class HttpResponseProxy implements CloseableHttpResponse { - - private final HttpResponse original; - private final ConnectionHolder connHolder; - - public HttpResponseProxy(final HttpResponse original, final ConnectionHolder connHolder) { - this.original = original; - this.connHolder = connHolder; - ResponseEntityProxy.enchance(original, connHolder); - } - - public void close() throws IOException { - if (this.connHolder != null) { - this.connHolder.abortConnection(); - } - } - - public StatusLine getStatusLine() { - return original.getStatusLine(); - } - - public void setStatusLine(final StatusLine statusline) { - original.setStatusLine(statusline); - } - - public void setStatusLine(final ProtocolVersion ver, final int code) { - original.setStatusLine(ver, code); - } - - public void setStatusLine(final ProtocolVersion ver, final int code, final String reason) { - original.setStatusLine(ver, code, reason); - } - - public void setStatusCode(final int code) throws IllegalStateException { - original.setStatusCode(code); - } - - public void setReasonPhrase(final String reason) throws IllegalStateException { - original.setReasonPhrase(reason); - } - - public HttpEntity getEntity() { - return original.getEntity(); - } - - public void setEntity(final HttpEntity entity) { - original.setEntity(entity); - } - - public Locale getLocale() { - return original.getLocale(); - } - - public void setLocale(final Locale loc) { - original.setLocale(loc); - } - - public ProtocolVersion getProtocolVersion() { - return original.getProtocolVersion(); - } - - public boolean containsHeader(final String name) { - return original.containsHeader(name); - } - - public Header[] getHeaders(final String name) { - return original.getHeaders(name); - } - - public Header getFirstHeader(final String name) { - return original.getFirstHeader(name); - } - - public Header getLastHeader(final String name) { - return original.getLastHeader(name); - } - - public Header[] getAllHeaders() { - return original.getAllHeaders(); - } - - public void addHeader(final Header header) { - original.addHeader(header); - } - - public void addHeader(final String name, final String value) { - original.addHeader(name, value); - } - - public void setHeader(final Header header) { - original.setHeader(header); - } - - public void setHeader(final String name, final String value) { - original.setHeader(name, value); - } - - public void setHeaders(final Header[] headers) { - original.setHeaders(headers); - } - - public void removeHeader(final Header header) { - original.removeHeader(header); - } - - public void removeHeaders(final String name) { - original.removeHeaders(name); - } - - public HeaderIterator headerIterator() { - return original.headerIterator(); - } - - public HeaderIterator headerIterator(final String name) { - return original.headerIterator(name); - } - - @Deprecated - public HttpParams getParams() { - return original.getParams(); - } - - @Deprecated - public void setParams(final HttpParams params) { - original.setParams(params); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("HttpResponseProxy{"); - sb.append(original); - sb.append('}'); - return sb.toString(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/MainClientExec.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/MainClientExec.java deleted file mode 100644 index 5a2a426a..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/MainClientExec.java +++ /dev/null @@ -1,584 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.execchain; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; - -import android.util.Log; - -import org.apache.http.ConnectionReuseStrategy; -import org.apache.http.HttpClientConnection; -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.Immutable; -import org.apache.http.auth.AUTH; -import org.apache.http.auth.AuthProtocolState; -import org.apache.http.auth.AuthStateHC4; -import org.apache.http.client.AuthenticationStrategy; -import org.apache.http.client.NonRepeatableRequestException; -import org.apache.http.client.UserTokenHandler; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpExecutionAware; -import org.apache.http.client.methods.HttpRequestWrapper; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.client.protocol.RequestClientConnControl; -import org.apache.http.conn.ConnectionKeepAliveStrategy; -import org.apache.http.conn.ConnectionRequest; -import org.apache.http.conn.HttpClientConnectionManager; -import org.apache.http.conn.routing.BasicRouteDirector; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.conn.routing.HttpRouteDirector; -import org.apache.http.conn.routing.RouteTracker; -import org.apache.http.entity.BufferedHttpEntityHC4; -import org.apache.http.impl.auth.HttpAuthenticator; -import org.apache.http.impl.conn.ConnectionShutdownException; -import org.apache.http.message.BasicHttpRequest; -import org.apache.http.protocol.HttpCoreContext; -import org.apache.http.protocol.HttpProcessor; -import org.apache.http.protocol.HttpRequestExecutor; -import org.apache.http.protocol.ImmutableHttpProcessor; -import org.apache.http.protocol.RequestTargetHostHC4; -import org.apache.http.util.Args; -import org.apache.http.util.EntityUtilsHC4; - -/** - * The last request executor in the HTTP request execution chain - * that is responsible for execution of request / response - * exchanges with the opposite endpoint. - * This executor will automatically retry the request in case - * of an authentication challenge by an intermediate proxy or - * by the target server. - * - * @since 4.3 - */ -@Immutable -public class MainClientExec implements ClientExecChain { - - private final static String TAG = "HttpClient"; - - private final HttpRequestExecutor requestExecutor; - private final HttpClientConnectionManager connManager; - private final ConnectionReuseStrategy reuseStrategy; - private final ConnectionKeepAliveStrategy keepAliveStrategy; - private final HttpProcessor proxyHttpProcessor; - private final AuthenticationStrategy targetAuthStrategy; - private final AuthenticationStrategy proxyAuthStrategy; - private final HttpAuthenticator authenticator; - private final UserTokenHandler userTokenHandler; - private final HttpRouteDirector routeDirector; - - - public MainClientExec( - final HttpRequestExecutor requestExecutor, - final HttpClientConnectionManager connManager, - final ConnectionReuseStrategy reuseStrategy, - final ConnectionKeepAliveStrategy keepAliveStrategy, - final AuthenticationStrategy targetAuthStrategy, - final AuthenticationStrategy proxyAuthStrategy, - final UserTokenHandler userTokenHandler) { - Args.notNull(requestExecutor, "HTTP request executor"); - Args.notNull(connManager, "Client connection manager"); - Args.notNull(reuseStrategy, "Connection reuse strategy"); - Args.notNull(keepAliveStrategy, "Connection keep alive strategy"); - Args.notNull(targetAuthStrategy, "Target authentication strategy"); - Args.notNull(proxyAuthStrategy, "Proxy authentication strategy"); - Args.notNull(userTokenHandler, "User token handler"); - this.authenticator = new HttpAuthenticator(); - this.proxyHttpProcessor = new ImmutableHttpProcessor( - new RequestTargetHostHC4(), new RequestClientConnControl()); - this.routeDirector = new BasicRouteDirector(); - this.requestExecutor = requestExecutor; - this.connManager = connManager; - this.reuseStrategy = reuseStrategy; - this.keepAliveStrategy = keepAliveStrategy; - this.targetAuthStrategy = targetAuthStrategy; - this.proxyAuthStrategy = proxyAuthStrategy; - this.userTokenHandler = userTokenHandler; - } - - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, - final HttpClientContext context, - final HttpExecutionAware execAware) throws IOException, HttpException { - Args.notNull(route, "HTTP route"); - Args.notNull(request, "HTTP request"); - Args.notNull(context, "HTTP context"); - - AuthStateHC4 targetAuthState = context.getTargetAuthState(); - if (targetAuthState == null) { - targetAuthState = new AuthStateHC4(); - context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, targetAuthState); - } - AuthStateHC4 proxyAuthState = context.getProxyAuthState(); - if (proxyAuthState == null) { - proxyAuthState = new AuthStateHC4(); - context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxyAuthState); - } - - if (request instanceof HttpEntityEnclosingRequest) { - RequestEntityProxy.enhance((HttpEntityEnclosingRequest) request); - } - - Object userToken = context.getUserToken(); - - final ConnectionRequest connRequest = connManager.requestConnection(route, userToken); - if (execAware != null) { - if (execAware.isAborted()) { - connRequest.cancel(); - throw new RequestAbortedException("Request aborted"); - } else { - execAware.setCancellable(connRequest); - } - } - - final RequestConfig config = context.getRequestConfig(); - - final HttpClientConnection managedConn; - try { - final int timeout = config.getConnectionRequestTimeout(); - managedConn = connRequest.get(timeout > 0 ? timeout : 0, TimeUnit.MILLISECONDS); - } catch(final InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new RequestAbortedException("Request aborted", interrupted); - } catch(final ExecutionException ex) { - Throwable cause = ex.getCause(); - if (cause == null) { - cause = ex; - } - throw new RequestAbortedException("Request execution failed", cause); - } - - context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn); - - if (config.isStaleConnectionCheckEnabled()) { - // validate connection - if (managedConn.isOpen()) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Stale connection check"); - } - if (managedConn.isStale()) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Stale connection detected"); - } - managedConn.close(); - } - } - } - - final ConnectionHolder connHolder = new ConnectionHolder(this.connManager, managedConn); - try { - if (execAware != null) { - execAware.setCancellable(connHolder); - } - - HttpResponse response; - for (int execCount = 1;; execCount++) { - - if (execCount > 1 && !RequestEntityProxy.isRepeatable(request)) { - throw new NonRepeatableRequestException("Cannot retry request " + - "with a non-repeatable request entity."); - } - - if (execAware != null && execAware.isAborted()) { - throw new RequestAbortedException("Request aborted"); - } - - if (!managedConn.isOpen()) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Opening connection " + route); - } - try { - establishRoute(proxyAuthState, managedConn, route, request, context); - } catch (final TunnelRefusedException ex) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, ex.getMessage()); - } - response = ex.getResponse(); - break; - } - } - final int timeout = config.getSocketTimeout(); - if (timeout >= 0) { - managedConn.setSocketTimeout(timeout); - } - - if (execAware != null && execAware.isAborted()) { - throw new RequestAbortedException("Request aborted"); - } - - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Executing request " + request.getRequestLine()); - } - - if (!request.containsHeader(AUTH.WWW_AUTH_RESP)) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Target auth state: " + targetAuthState.getState()); - } - this.authenticator.generateAuthResponse(request, targetAuthState, context); - } - if (!request.containsHeader(AUTH.PROXY_AUTH_RESP) && !route.isTunnelled()) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Proxy auth state: " + proxyAuthState.getState()); - } - this.authenticator.generateAuthResponse(request, proxyAuthState, context); - } - - response = requestExecutor.execute(request, managedConn, context); - - // The connection is in or can be brought to a re-usable state. - if (reuseStrategy.keepAlive(response, context)) { - // Set the idle duration of this connection - final long duration = keepAliveStrategy.getKeepAliveDuration(response, context); - if (Log.isLoggable(TAG, Log.DEBUG)) { - final String s; - if (duration > 0) { - s = "for " + duration + " " + TimeUnit.MILLISECONDS; - } else { - s = "indefinitely"; - } - Log.d(TAG, "Connection can be kept alive " + s); - } - connHolder.setValidFor(duration, TimeUnit.MILLISECONDS); - connHolder.markReusable(); - } else { - connHolder.markNonReusable(); - } - - if (needAuthentication( - targetAuthState, proxyAuthState, route, response, context)) { - // Make sure the response body is fully consumed, if present - final HttpEntity entity = response.getEntity(); - if (connHolder.isReusable()) { - EntityUtilsHC4.consume(entity); - } else { - managedConn.close(); - if (proxyAuthState.getState() == AuthProtocolState.SUCCESS - && proxyAuthState.getAuthScheme() != null - && proxyAuthState.getAuthScheme().isConnectionBased()) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Resetting proxy auth state"); - } - proxyAuthState.reset(); - } - if (targetAuthState.getState() == AuthProtocolState.SUCCESS - && targetAuthState.getAuthScheme() != null - && targetAuthState.getAuthScheme().isConnectionBased()) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Resetting target auth state"); - } - targetAuthState.reset(); - } - } - // discard previous auth headers - final HttpRequest original = request.getOriginal(); - if (!original.containsHeader(AUTH.WWW_AUTH_RESP)) { - request.removeHeaders(AUTH.WWW_AUTH_RESP); - } - if (!original.containsHeader(AUTH.PROXY_AUTH_RESP)) { - request.removeHeaders(AUTH.PROXY_AUTH_RESP); - } - } else { - break; - } - } - - if (userToken == null) { - userToken = userTokenHandler.getUserToken(context); - context.setAttribute(HttpClientContext.USER_TOKEN, userToken); - } - if (userToken != null) { - connHolder.setState(userToken); - } - - // check for entity, release connection if possible - final HttpEntity entity = response.getEntity(); - if (entity == null || !entity.isStreaming()) { - // connection not needed and (assumed to be) in re-usable state - connHolder.releaseConnection(); - return new HttpResponseProxy(response, null); - } else { - return new HttpResponseProxy(response, connHolder); - } - } catch (final ConnectionShutdownException ex) { - final InterruptedIOException ioex = new InterruptedIOException( - "Connection has been shut down"); - ioex.initCause(ex); - throw ioex; - } catch (final HttpException ex) { - connHolder.abortConnection(); - throw ex; - } catch (final IOException ex) { - connHolder.abortConnection(); - throw ex; - } catch (final RuntimeException ex) { - connHolder.abortConnection(); - throw ex; - } - } - - /** - * Establishes the target route. - */ - void establishRoute( - final AuthStateHC4 proxyAuthState, - final HttpClientConnection managedConn, - final HttpRoute route, - final HttpRequest request, - final HttpClientContext context) throws HttpException, IOException { - final RequestConfig config = context.getRequestConfig(); - final int timeout = config.getConnectTimeout(); - final RouteTracker tracker = new RouteTracker(route); - int step; - do { - final HttpRoute fact = tracker.toRoute(); - step = this.routeDirector.nextStep(route, fact); - - switch (step) { - - case HttpRouteDirector.CONNECT_TARGET: - this.connManager.connect( - managedConn, - route, - timeout > 0 ? timeout : 0, - context); - tracker.connectTarget(route.isSecure()); - break; - case HttpRouteDirector.CONNECT_PROXY: - this.connManager.connect( - managedConn, - route, - timeout > 0 ? timeout : 0, - context); - final HttpHost proxy = route.getProxyHost(); - tracker.connectProxy(proxy, false); - break; - case HttpRouteDirector.TUNNEL_TARGET: { - final boolean secure = createTunnelToTarget( - proxyAuthState, managedConn, route, request, context); - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Tunnel to target created."); - } - tracker.tunnelTarget(secure); - } break; - - case HttpRouteDirector.TUNNEL_PROXY: { - // The most simple example for this case is a proxy chain - // of two proxies, where P1 must be tunnelled to P2. - // route: Source -> P1 -> P2 -> Target (3 hops) - // fact: Source -> P1 -> Target (2 hops) - final int hop = fact.getHopCount()-1; // the hop to establish - final boolean secure = createTunnelToProxy(route, hop, context); - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Tunnel to proxy created."); - } - tracker.tunnelProxy(route.getHopTarget(hop), secure); - } break; - - case HttpRouteDirector.LAYER_PROTOCOL: - this.connManager.upgrade(managedConn, route, context); - tracker.layerProtocol(route.isSecure()); - break; - - case HttpRouteDirector.UNREACHABLE: - throw new HttpException("Unable to establish route: " + - "planned = " + route + "; current = " + fact); - case HttpRouteDirector.COMPLETE: - this.connManager.routeComplete(managedConn, route, context); - break; - default: - throw new IllegalStateException("Unknown step indicator " - + step + " from RouteDirector."); - } - - } while (step > HttpRouteDirector.COMPLETE); - } - - /** - * Creates a tunnel to the target server. - * The connection must be established to the (last) proxy. - * A CONNECT request for tunnelling through the proxy will - * be created and sent, the response received and checked. - * This method does not update the connection with - * information about the tunnel, that is left to the caller. - */ - private boolean createTunnelToTarget( - final AuthStateHC4 proxyAuthState, - final HttpClientConnection managedConn, - final HttpRoute route, - final HttpRequest request, - final HttpClientContext context) throws HttpException, IOException { - - final RequestConfig config = context.getRequestConfig(); - final int timeout = config.getConnectTimeout(); - - final HttpHost target = route.getTargetHost(); - final HttpHost proxy = route.getProxyHost(); - HttpResponse response = null; - - final String authority = target.toHostString(); - final HttpRequest connect = new BasicHttpRequest("CONNECT", authority, request.getProtocolVersion()); - - this.requestExecutor.preProcess(connect, this.proxyHttpProcessor, context); - - while (response == null) { - if (!managedConn.isOpen()) { - this.connManager.connect( - managedConn, - route, - timeout > 0 ? timeout : 0, - context); - } - - connect.removeHeaders(AUTH.PROXY_AUTH_RESP); - this.authenticator.generateAuthResponse(connect, proxyAuthState, context); - - response = this.requestExecutor.execute(connect, managedConn, context); - - final int status = response.getStatusLine().getStatusCode(); - if (status < 200) { - throw new HttpException("Unexpected response to CONNECT request: " + - response.getStatusLine()); - } - - if (config.isAuthenticationEnabled()) { - if (this.authenticator.isAuthenticationRequested(proxy, response, - this.proxyAuthStrategy, proxyAuthState, context)) { - if (this.authenticator.handleAuthChallenge(proxy, response, - this.proxyAuthStrategy, proxyAuthState, context)) { - // Retry request - if (this.reuseStrategy.keepAlive(response, context)) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Connection kept alive"); - } - // Consume response content - final HttpEntity entity = response.getEntity(); - EntityUtilsHC4.consume(entity); - } else { - managedConn.close(); - } - response = null; - } - } - } - } - - final int status = response.getStatusLine().getStatusCode(); - - if (status > 299) { - - // Buffer response content - final HttpEntity entity = response.getEntity(); - if (entity != null) { - response.setEntity(new BufferedHttpEntityHC4(entity)); - } - - managedConn.close(); - throw new TunnelRefusedException("CONNECT refused by proxy: " + - response.getStatusLine(), response); - } - - // How to decide on security of the tunnelled connection? - // The socket factory knows only about the segment to the proxy. - // Even if that is secure, the hop to the target may be insecure. - // Leave it to derived classes, consider insecure by default here. - return false; - } - - /** - * Creates a tunnel to an intermediate proxy. - * This method is not implemented in this class. - * It just throws an exception here. - */ - private boolean createTunnelToProxy( - final HttpRoute route, - final int hop, - final HttpClientContext context) throws HttpException { - - // Have a look at createTunnelToTarget and replicate the parts - // you need in a custom derived class. If your proxies don't require - // authentication, it is not too hard. But for the stock version of - // HttpClient, we cannot make such simplifying assumptions and would - // have to include proxy authentication code. The HttpComponents team - // is currently not in a position to support rarely used code of this - // complexity. Feel free to submit patches that refactor the code in - // createTunnelToTarget to facilitate re-use for proxy tunnelling. - - throw new HttpException("Proxy chains are not supported."); - } - - private boolean needAuthentication( - final AuthStateHC4 targetAuthState, - final AuthStateHC4 proxyAuthState, - final HttpRoute route, - final HttpResponse response, - final HttpClientContext context) { - final RequestConfig config = context.getRequestConfig(); - if (config.isAuthenticationEnabled()) { - HttpHost target = context.getTargetHost(); - if (target == null) { - target = route.getTargetHost(); - } - if (target.getPort() < 0) { - target = new HttpHost( - target.getHostName(), - route.getTargetHost().getPort(), - target.getSchemeName()); - } - final boolean targetAuthRequested = this.authenticator.isAuthenticationRequested( - target, response, this.targetAuthStrategy, targetAuthState, context); - - HttpHost proxy = route.getProxyHost(); - // if proxy is not set use target host instead - if (proxy == null) { - proxy = route.getTargetHost(); - } - final boolean proxyAuthRequested = this.authenticator.isAuthenticationRequested( - proxy, response, this.proxyAuthStrategy, proxyAuthState, context); - - if (targetAuthRequested) { - return this.authenticator.handleAuthChallenge(target, response, - this.targetAuthStrategy, targetAuthState, context); - } - if (proxyAuthRequested) { - return this.authenticator.handleAuthChallenge(proxy, response, - this.proxyAuthStrategy, proxyAuthState, context); - } - } - return false; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/MinimalClientExec.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/MinimalClientExec.java deleted file mode 100644 index 64c8ba1e..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/MinimalClientExec.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.execchain; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; - -import org.apache.http.ConnectionReuseStrategy; -import org.apache.http.HttpClientConnection; -import org.apache.http.HttpEntity; -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.ProtocolException; -import org.apache.http.annotation.Immutable; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpExecutionAware; -import org.apache.http.client.methods.HttpRequestWrapper; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.client.protocol.RequestClientConnControl; -import org.apache.http.client.utils.URIUtilsHC4; -import org.apache.http.conn.ConnectionKeepAliveStrategy; -import org.apache.http.conn.ConnectionRequest; -import org.apache.http.conn.HttpClientConnectionManager; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.impl.conn.ConnectionShutdownException; -import org.apache.http.protocol.HttpCoreContext; -import org.apache.http.protocol.HttpProcessor; -import org.apache.http.protocol.HttpRequestExecutor; -import org.apache.http.protocol.ImmutableHttpProcessor; -import org.apache.http.protocol.RequestContentHC4; -import org.apache.http.protocol.RequestTargetHostHC4; -import org.apache.http.protocol.RequestUserAgentHC4; -import org.apache.http.util.Args; -import org.apache.http.util.VersionInfoHC4; - -/** - * Request executor that implements the most fundamental aspects of - * the HTTP specification and the most straight-forward request / response - * exchange with the target server. This executor does not support - * execution via proxy and will make no attempts to retry the request - * in case of a redirect, authentication challenge or I/O error. - * - * @since 4.3 - */ -@Immutable -public class MinimalClientExec implements ClientExecChain { - - private final HttpRequestExecutor requestExecutor; - private final HttpClientConnectionManager connManager; - private final ConnectionReuseStrategy reuseStrategy; - private final ConnectionKeepAliveStrategy keepAliveStrategy; - private final HttpProcessor httpProcessor; - - public MinimalClientExec( - final HttpRequestExecutor requestExecutor, - final HttpClientConnectionManager connManager, - final ConnectionReuseStrategy reuseStrategy, - final ConnectionKeepAliveStrategy keepAliveStrategy) { - Args.notNull(requestExecutor, "HTTP request executor"); - Args.notNull(connManager, "Client connection manager"); - Args.notNull(reuseStrategy, "Connection reuse strategy"); - Args.notNull(keepAliveStrategy, "Connection keep alive strategy"); - this.httpProcessor = new ImmutableHttpProcessor( - new RequestContentHC4(), - new RequestTargetHostHC4(), - new RequestClientConnControl(), - new RequestUserAgentHC4(VersionInfoHC4.getUserAgent( - "Apache-HttpClient", "org.apache.http.client", getClass()))); - this.requestExecutor = requestExecutor; - this.connManager = connManager; - this.reuseStrategy = reuseStrategy; - this.keepAliveStrategy = keepAliveStrategy; - } - - static void rewriteRequestURI( - final HttpRequestWrapper request, - final HttpRoute route) throws ProtocolException { - try { - URI uri = request.getURI(); - if (uri != null) { - // Make sure the request URI is relative - if (uri.isAbsolute()) { - uri = URIUtilsHC4.rewriteURI(uri, null, true); - } else { - uri = URIUtilsHC4.rewriteURI(uri); - } - request.setURI(uri); - } - } catch (final URISyntaxException ex) { - throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex); - } - } - - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, - final HttpClientContext context, - final HttpExecutionAware execAware) throws IOException, HttpException { - Args.notNull(route, "HTTP route"); - Args.notNull(request, "HTTP request"); - Args.notNull(context, "HTTP context"); - - rewriteRequestURI(request, route); - - final ConnectionRequest connRequest = connManager.requestConnection(route, null); - if (execAware != null) { - if (execAware.isAborted()) { - connRequest.cancel(); - throw new RequestAbortedException("Request aborted"); - } else { - execAware.setCancellable(connRequest); - } - } - - final RequestConfig config = context.getRequestConfig(); - - final HttpClientConnection managedConn; - try { - final int timeout = config.getConnectionRequestTimeout(); - managedConn = connRequest.get(timeout > 0 ? timeout : 0, TimeUnit.MILLISECONDS); - } catch(final InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new RequestAbortedException("Request aborted", interrupted); - } catch(final ExecutionException ex) { - Throwable cause = ex.getCause(); - if (cause == null) { - cause = ex; - } - throw new RequestAbortedException("Request execution failed", cause); - } - - final ConnectionHolder releaseTrigger = new ConnectionHolder(connManager, managedConn); - try { - if (execAware != null) { - if (execAware.isAborted()) { - releaseTrigger.close(); - throw new RequestAbortedException("Request aborted"); - } else { - execAware.setCancellable(releaseTrigger); - } - } - - if (!managedConn.isOpen()) { - final int timeout = config.getConnectTimeout(); - this.connManager.connect( - managedConn, - route, - timeout > 0 ? timeout : 0, - context); - this.connManager.routeComplete(managedConn, route, context); - } - final int timeout = config.getSocketTimeout(); - if (timeout >= 0) { - managedConn.setSocketTimeout(timeout); - } - - HttpHost target = null; - final HttpRequest original = request.getOriginal(); - if (original instanceof HttpUriRequest) { - final URI uri = ((HttpUriRequest) original).getURI(); - if (uri.isAbsolute()) { - target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); - } - } - if (target == null) { - target = route.getTargetHost(); - } - - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); - context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); - context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn); - context.setAttribute(HttpClientContext.HTTP_ROUTE, route); - - httpProcessor.process(request, context); - final HttpResponse response = requestExecutor.execute(request, managedConn, context); - httpProcessor.process(response, context); - - // The connection is in or can be brought to a re-usable state. - if (reuseStrategy.keepAlive(response, context)) { - // Set the idle duration of this connection - final long duration = keepAliveStrategy.getKeepAliveDuration(response, context); - releaseTrigger.setValidFor(duration, TimeUnit.MILLISECONDS); - releaseTrigger.markReusable(); - } else { - releaseTrigger.markNonReusable(); - } - - // check for entity, release connection if possible - final HttpEntity entity = response.getEntity(); - if (entity == null || !entity.isStreaming()) { - // connection not needed and (assumed to be) in re-usable state - releaseTrigger.releaseConnection(); - return new HttpResponseProxy(response, null); - } else { - return new HttpResponseProxy(response, releaseTrigger); - } - } catch (final ConnectionShutdownException ex) { - final InterruptedIOException ioex = new InterruptedIOException( - "Connection has been shut down"); - ioex.initCause(ex); - throw ioex; - } catch (final HttpException ex) { - releaseTrigger.abortConnection(); - throw ex; - } catch (final IOException ex) { - releaseTrigger.abortConnection(); - throw ex; - } catch (final RuntimeException ex) { - releaseTrigger.abortConnection(); - throw ex; - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/ProtocolExec.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/ProtocolExec.java deleted file mode 100644 index dce73ff8..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/ProtocolExec.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.execchain; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -import android.util.Log; - -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.ProtocolException; -import org.apache.http.annotation.Immutable; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpExecutionAware; -import org.apache.http.client.methods.HttpRequestWrapper; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.params.ClientPNames; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.client.utils.URIUtilsHC4; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.impl.client.BasicCredentialsProviderHC4; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HttpCoreContext; -import org.apache.http.protocol.HttpProcessor; -import org.apache.http.util.Args; - -/** - * Request executor in the request execution chain that is responsible - * for implementation of HTTP specification requirements. - * Internally this executor relies on a {@link HttpProcessor} to populate - * requisite HTTP request headers, process HTTP response headers and update - * session state in {@link HttpClientContext}. - *

    - * Further responsibilities such as communication with the opposite - * endpoint is delegated to the next executor in the request execution - * chain. - * - * @since 4.3 - */ -@Immutable -@SuppressWarnings("deprecation") -public class ProtocolExec implements ClientExecChain { - - private final static String TAG = "HttpClient"; - - private final ClientExecChain requestExecutor; - private final HttpProcessor httpProcessor; - - public ProtocolExec(final ClientExecChain requestExecutor, final HttpProcessor httpProcessor) { - Args.notNull(requestExecutor, "HTTP client request executor"); - Args.notNull(httpProcessor, "HTTP protocol processor"); - this.requestExecutor = requestExecutor; - this.httpProcessor = httpProcessor; - } - - void rewriteRequestURI( - final HttpRequestWrapper request, - final HttpRoute route) throws ProtocolException { - try { - URI uri = request.getURI(); - if (uri != null) { - if (route.getProxyHost() != null && !route.isTunnelled()) { - // Make sure the request URI is absolute - if (!uri.isAbsolute()) { - final HttpHost target = route.getTargetHost(); - uri = URIUtilsHC4.rewriteURI(uri, target, true); - } else { - uri = URIUtilsHC4.rewriteURI(uri); - } - } else { - // Make sure the request URI is relative - if (uri.isAbsolute()) { - uri = URIUtilsHC4.rewriteURI(uri, null, true); - } else { - uri = URIUtilsHC4.rewriteURI(uri); - } - } - request.setURI(uri); - } - } catch (final URISyntaxException ex) { - throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex); - } - } - - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, - final HttpClientContext context, - final HttpExecutionAware execAware) throws IOException, - HttpException { - Args.notNull(route, "HTTP route"); - Args.notNull(request, "HTTP request"); - Args.notNull(context, "HTTP context"); - - final HttpRequest original = request.getOriginal(); - URI uri = null; - if (original instanceof HttpUriRequest) { - uri = ((HttpUriRequest) original).getURI(); - } else { - final String uriString = original.getRequestLine().getUri(); - try { - uri = URI.create(uriString); - } catch (final IllegalArgumentException ex) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Unable to parse '" + uriString + "' as a valid URI; " + - "request URI and Host header may be inconsistent", ex); - } - } - - } - request.setURI(uri); - - // Re-write request URI if needed - rewriteRequestURI(request, route); - - final HttpParams params = request.getParams(); - HttpHost virtualHost = (HttpHost) params.getParameter(ClientPNames.VIRTUAL_HOST); - // HTTPCLIENT-1092 - add the port if necessary - if (virtualHost != null && virtualHost.getPort() == -1) { - final int port = route.getTargetHost().getPort(); - if (port != -1) { - virtualHost = new HttpHost(virtualHost.getHostName(), port, - virtualHost.getSchemeName()); - } - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Using virtual host" + virtualHost); - } - } - - HttpHost target = null; - if (virtualHost != null) { - target = virtualHost; - } else { - if (uri != null && uri.isAbsolute() && uri.getHost() != null) { - target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); - } - } - if (target == null) { - target = route.getTargetHost(); - } - - // Get user info from the URI - if (uri != null) { - final String userinfo = uri.getUserInfo(); - if (userinfo != null) { - CredentialsProvider credsProvider = context.getCredentialsProvider(); - if (credsProvider == null) { - credsProvider = new BasicCredentialsProviderHC4(); - context.setCredentialsProvider(credsProvider); - } - credsProvider.setCredentials( - new AuthScope(target.getHostName(), target.getPort()), - new UsernamePasswordCredentials(userinfo)); - } - } - - // Run request protocol interceptors - context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); - context.setAttribute(HttpClientContext.HTTP_ROUTE, route); - context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); - - this.httpProcessor.process(request, context); - - final CloseableHttpResponse response = this.requestExecutor.execute(route, request, - context, execAware); - try { - // Run response protocol interceptors - context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response); - this.httpProcessor.process(response, context); - return response; - } catch (final RuntimeException ex) { - response.close(); - throw ex; - } catch (final IOException ex) { - response.close(); - throw ex; - } catch (final HttpException ex) { - response.close(); - throw ex; - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/RedirectExec.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/RedirectExec.java deleted file mode 100644 index 9b3c58ca..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/RedirectExec.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.execchain; - -import java.io.IOException; -import java.net.URI; -import java.util.List; - -import android.util.Log; - -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.ProtocolException; -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AuthStateHC4; -import org.apache.http.client.RedirectException; -import org.apache.http.client.RedirectStrategy; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpExecutionAware; -import org.apache.http.client.methods.HttpRequestWrapper; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.client.utils.URIUtilsHC4; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.conn.routing.HttpRoutePlanner; -import org.apache.http.util.Args; -import org.apache.http.util.EntityUtilsHC4; - -/** - * Request executor in the request execution chain that is responsible - * for handling of request redirects. - *

    - * Further responsibilities such as communication with the opposite - * endpoint is delegated to the next executor in the request execution - * chain. - * - * @since 4.3 - */ -@ThreadSafe -public class RedirectExec implements ClientExecChain { - - private final static String TAG = "HttpClient"; - - private final ClientExecChain requestExecutor; - private final RedirectStrategy redirectStrategy; - private final HttpRoutePlanner routePlanner; - - public RedirectExec( - final ClientExecChain requestExecutor, - final HttpRoutePlanner routePlanner, - final RedirectStrategy redirectStrategy) { - super(); - Args.notNull(requestExecutor, "HTTP client request executor"); - Args.notNull(routePlanner, "HTTP route planner"); - Args.notNull(redirectStrategy, "HTTP redirect strategy"); - this.requestExecutor = requestExecutor; - this.routePlanner = routePlanner; - this.redirectStrategy = redirectStrategy; - } - - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, - final HttpClientContext context, - final HttpExecutionAware execAware) throws IOException, HttpException { - Args.notNull(route, "HTTP route"); - Args.notNull(request, "HTTP request"); - Args.notNull(context, "HTTP context"); - - final List redirectLocations = context.getRedirectLocations(); - if (redirectLocations != null) { - redirectLocations.clear(); - } - - final RequestConfig config = context.getRequestConfig(); - final int maxRedirects = config.getMaxRedirects() > 0 ? config.getMaxRedirects() : 50; - HttpRoute currentRoute = route; - HttpRequestWrapper currentRequest = request; - for (int redirectCount = 0;;) { - final CloseableHttpResponse response = requestExecutor.execute( - currentRoute, currentRequest, context, execAware); - try { - if (config.isRedirectsEnabled() && - this.redirectStrategy.isRedirected(currentRequest, response, context)) { - - if (redirectCount >= maxRedirects) { - throw new RedirectException("Maximum redirects ("+ maxRedirects + ") exceeded"); - } - redirectCount++; - - final HttpRequest redirect = this.redirectStrategy.getRedirect( - currentRequest, response, context); - if (!redirect.headerIterator().hasNext()) { - final HttpRequest original = request.getOriginal(); - redirect.setHeaders(original.getAllHeaders()); - } - currentRequest = HttpRequestWrapper.wrap(redirect); - - if (currentRequest instanceof HttpEntityEnclosingRequest) { - RequestEntityProxy.enhance((HttpEntityEnclosingRequest) currentRequest); - } - - final URI uri = currentRequest.getURI(); - final HttpHost newTarget = URIUtilsHC4.extractHost(uri); - if (newTarget == null) { - throw new ProtocolException("Redirect URI does not specify a valid host name: " + - uri); - } - - // Reset virtual host and auth states if redirecting to another host - if (!currentRoute.getTargetHost().equals(newTarget)) { - final AuthStateHC4 targetAuthState = context.getTargetAuthState(); - if (targetAuthState != null) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Resetting target auth state"); - } - targetAuthState.reset(); - } - final AuthStateHC4 proxyAuthState = context.getProxyAuthState(); - if (proxyAuthState != null) { - final AuthScheme authScheme = proxyAuthState.getAuthScheme(); - if (authScheme != null && authScheme.isConnectionBased()) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Resetting proxy auth state"); - } - proxyAuthState.reset(); - } - } - } - - currentRoute = this.routePlanner.determineRoute(newTarget, currentRequest, context); - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Redirecting to '" + uri + "' via " + currentRoute); - } - EntityUtilsHC4.consume(response.getEntity()); - response.close(); - } else { - return response; - } - } catch (final RuntimeException ex) { - response.close(); - throw ex; - } catch (final IOException ex) { - response.close(); - throw ex; - } catch (final HttpException ex) { - // Protocol exception related to a direct. - // The underlying connection may still be salvaged. - try { - EntityUtilsHC4.consume(response.getEntity()); - } catch (final IOException ioex) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "I/O error while releasing connection", ioex); - } - } finally { - response.close(); - } - throw ex; - } - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/RequestAbortedException.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/RequestAbortedException.java deleted file mode 100644 index 2a3d0a5f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/RequestAbortedException.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.execchain; - -import java.io.InterruptedIOException; - -import org.apache.http.annotation.Immutable; - -/** - * Signals that the request has been aborted. - * - * @since 4.3 - */ -@Immutable -public class RequestAbortedException extends InterruptedIOException { - - private static final long serialVersionUID = 4973849966012490112L; - - public RequestAbortedException(final String message) { - super(message); - } - - public RequestAbortedException(final String message, final Throwable cause) { - super(message); - if (cause != null) { - initCause(cause); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/RequestEntityProxy.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/RequestEntityProxy.java deleted file mode 100644 index 20f50011..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/RequestEntityProxy.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.execchain; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpRequest; -import org.apache.http.annotation.NotThreadSafe; - -/** - * A Proxy class for {@link org.apache.http.HttpEntity} enclosed in a request message. - * - * @since 4.3 - */ -@NotThreadSafe -class RequestEntityProxy implements HttpEntity { - - static void enhance(final HttpEntityEnclosingRequest request) { - final HttpEntity entity = request.getEntity(); - if (entity != null && !entity.isRepeatable() && !isEnhanced(entity)) { - request.setEntity(new RequestEntityProxy(entity)); - } - } - - static boolean isEnhanced(final HttpEntity entity) { - return entity instanceof RequestEntityProxy; - } - - static boolean isRepeatable(final HttpRequest request) { - if (request instanceof HttpEntityEnclosingRequest) { - final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); - if (entity != null) { - if (isEnhanced(entity)) { - final RequestEntityProxy proxy = (RequestEntityProxy) entity; - if (!proxy.isConsumed()) { - return true; - } - } - return entity.isRepeatable(); - } - } - return true; - } - - private final HttpEntity original; - private boolean consumed = false; - - RequestEntityProxy(final HttpEntity original) { - super(); - this.original = original; - } - - public HttpEntity getOriginal() { - return original; - } - - public boolean isConsumed() { - return consumed; - } - - public boolean isRepeatable() { - return original.isRepeatable(); - } - - public boolean isChunked() { - return original.isChunked(); - } - - public long getContentLength() { - return original.getContentLength(); - } - - public Header getContentType() { - return original.getContentType(); - } - - public Header getContentEncoding() { - return original.getContentEncoding(); - } - - public InputStream getContent() throws IOException, IllegalStateException { - return original.getContent(); - } - - public void writeTo(final OutputStream outstream) throws IOException { - consumed = true; - original.writeTo(outstream); - } - - public boolean isStreaming() { - return original.isStreaming(); - } - - @Deprecated - public void consumeContent() throws IOException { - consumed = true; - original.consumeContent(); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("RequestEntityProxy{"); - sb.append(original); - sb.append('}'); - return sb.toString(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/ResponseEntityProxy.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/ResponseEntityProxy.java deleted file mode 100644 index 311ff392..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/ResponseEntityProxy.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.execchain; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.SocketException; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.conn.EofSensorInputStreamHC4; -import org.apache.http.conn.EofSensorWatcher; -import org.apache.http.entity.HttpEntityWrapperHC4; - -/** - * A wrapper class for {@link HttpEntity} enclosed in a response message. - * - * @since 4.3 - */ -@NotThreadSafe -class ResponseEntityProxy extends HttpEntityWrapperHC4 implements EofSensorWatcher { - - private final ConnectionHolder connHolder; - - public static void enchance(final HttpResponse response, final ConnectionHolder connHolder) { - final HttpEntity entity = response.getEntity(); - if (entity != null && entity.isStreaming() && connHolder != null) { - response.setEntity(new ResponseEntityProxy(entity, connHolder)); - } - } - - ResponseEntityProxy(final HttpEntity entity, final ConnectionHolder connHolder) { - super(entity); - this.connHolder = connHolder; - } - - private void cleanup() { - if (this.connHolder != null) { - this.connHolder.abortConnection(); - } - } - - public void releaseConnection() throws IOException { - if (this.connHolder != null) { - try { - if (this.connHolder.isReusable()) { - this.connHolder.releaseConnection(); - } - } finally { - cleanup(); - } - } - } - - @Override - public boolean isRepeatable() { - return false; - } - - @Override - public InputStream getContent() throws IOException { - return new EofSensorInputStreamHC4(this.wrappedEntity.getContent(), this); - } - - @Deprecated - @Override - public void consumeContent() throws IOException { - releaseConnection(); - } - - @Override - public void writeTo(final OutputStream outstream) throws IOException { - try { - this.wrappedEntity.writeTo(outstream); - releaseConnection(); - } finally { - cleanup(); - } - } - - public boolean eofDetected(final InputStream wrapped) throws IOException { - try { - // there may be some cleanup required, such as - // reading trailers after the response body: - wrapped.close(); - releaseConnection(); - } finally { - cleanup(); - } - return false; - } - - public boolean streamClosed(final InputStream wrapped) throws IOException { - try { - final boolean open = connHolder != null && !connHolder.isReleased(); - // this assumes that closing the stream will - // consume the remainder of the response body: - try { - wrapped.close(); - releaseConnection(); - } catch (final SocketException ex) { - if (open) { - throw ex; - } - } - } finally { - cleanup(); - } - return false; - } - - public boolean streamAbort(final InputStream wrapped) throws IOException { - cleanup(); - return false; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("ResponseEntityProxy{"); - sb.append(wrappedEntity); - sb.append('}'); - return sb.toString(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/RetryExec.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/RetryExec.java deleted file mode 100644 index af987eea..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/RetryExec.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.execchain; - -import java.io.IOException; - -import android.util.Log; - -import org.apache.http.Header; -import org.apache.http.HttpException; -import org.apache.http.NoHttpResponseException; -import org.apache.http.annotation.Immutable; -import org.apache.http.client.HttpRequestRetryHandler; -import org.apache.http.client.NonRepeatableRequestException; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpExecutionAware; -import org.apache.http.client.methods.HttpRequestWrapper; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.util.Args; - -/** - * Request executor in the request execution chain that is responsible - * for making a decision whether a request failed due to an I/O error - * should be re-executed. - *

    - * Further responsibilities such as communication with the opposite - * endpoint is delegated to the next executor in the request execution - * chain. - * - * @since 4.3 - */ -@Immutable -public class RetryExec implements ClientExecChain { - - private final static String TAG = "HttpClient"; - - private final ClientExecChain requestExecutor; - private final HttpRequestRetryHandler retryHandler; - - public RetryExec( - final ClientExecChain requestExecutor, - final HttpRequestRetryHandler retryHandler) { - Args.notNull(requestExecutor, "HTTP request executor"); - Args.notNull(retryHandler, "HTTP request retry handler"); - this.requestExecutor = requestExecutor; - this.retryHandler = retryHandler; - } - - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, - final HttpClientContext context, - final HttpExecutionAware execAware) throws IOException, HttpException { - Args.notNull(route, "HTTP route"); - Args.notNull(request, "HTTP request"); - Args.notNull(context, "HTTP context"); - final Header[] origheaders = request.getAllHeaders(); - for (int execCount = 1;; execCount++) { - try { - return this.requestExecutor.execute(route, request, context, execAware); - } catch (final IOException ex) { - if (execAware != null && execAware.isAborted()) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Request has been aborted"); - } - throw ex; - } - if (retryHandler.retryRequest(ex, execCount, context)) { - if (Log.isLoggable(TAG, Log.INFO)) { - Log.i(TAG, "I/O exception ("+ ex.getClass().getName() + - ") caught when processing request to " - + route + - ": " - + ex.getMessage()); - } - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, ex.getMessage(), ex); - } - if (!RequestEntityProxy.isRepeatable(request)) { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Cannot retry non-repeatable request"); - } - final NonRepeatableRequestException nreex = new NonRepeatableRequestException( - "Cannot retry request with a non-repeatable request entity"); - nreex.initCause(ex); - } - request.setHeaders(origheaders); - if (Log.isLoggable(TAG, Log.INFO)) { - Log.i(TAG, "Retrying request to " + route); - } - } else { - if (ex instanceof NoHttpResponseException) { - final NoHttpResponseException updatedex = new NoHttpResponseException( - route.getTargetHost().toHostString() + " failed to respond"); - updatedex.setStackTrace(ex.getStackTrace()); - throw updatedex; - } else { - throw ex; - } - } - } - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/ServiceUnavailableRetryExec.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/ServiceUnavailableRetryExec.java deleted file mode 100644 index d2d391c0..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/ServiceUnavailableRetryExec.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.execchain; - -import java.io.IOException; -import java.io.InterruptedIOException; - -import android.util.Log; - -import org.apache.http.Header; -import org.apache.http.HttpException; -import org.apache.http.annotation.Immutable; -import org.apache.http.client.ServiceUnavailableRetryStrategy; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpExecutionAware; -import org.apache.http.client.methods.HttpRequestWrapper; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.util.Args; - -/** - * Request executor in the request execution chain that is responsible - * for making a decision whether a request that received a non-2xx response - * from the target server should be re-executed. - *

    - * Further responsibilities such as communication with the opposite - * endpoint is delegated to the next executor in the request execution - * chain. - * - * @since 4.3 - */ -@Immutable -public class ServiceUnavailableRetryExec implements ClientExecChain { - - private final static String TAG = "HttpClient"; - - private final ClientExecChain requestExecutor; - private final ServiceUnavailableRetryStrategy retryStrategy; - - public ServiceUnavailableRetryExec( - final ClientExecChain requestExecutor, - final ServiceUnavailableRetryStrategy retryStrategy) { - super(); - Args.notNull(requestExecutor, "HTTP request executor"); - Args.notNull(retryStrategy, "Retry strategy"); - this.requestExecutor = requestExecutor; - this.retryStrategy = retryStrategy; - } - - public CloseableHttpResponse execute( - final HttpRoute route, - final HttpRequestWrapper request, - final HttpClientContext context, - final HttpExecutionAware execAware) throws IOException, HttpException { - final Header[] origheaders = request.getAllHeaders(); - for (int c = 1;; c++) { - final CloseableHttpResponse response = this.requestExecutor.execute( - route, request, context, execAware); - try { - if (this.retryStrategy.retryRequest(response, c, context)) { - response.close(); - final long nextInterval = this.retryStrategy.getRetryInterval(); - if (nextInterval > 0) { - try { - if (Log.isLoggable(TAG, Log.DEBUG)) { - Log.d(TAG, "Wait for " + nextInterval); - } - Thread.sleep(nextInterval); - } catch (final InterruptedException e) { - Thread.currentThread().interrupt(); - throw new InterruptedIOException(); - } - } - request.setHeaders(origheaders); - } else { - return response; - } - } catch (final RuntimeException ex) { - response.close(); - throw ex; - } - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/TunnelRefusedException.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/TunnelRefusedException.java deleted file mode 100644 index cff1e079..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/TunnelRefusedException.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.execchain; - -import org.apache.http.HttpException; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.Immutable; - -/** - * Signals that the tunnel request was rejected by the proxy host. - * - * @since 4.0 - */ -@Immutable -public class TunnelRefusedException extends HttpException { - - private static final long serialVersionUID = -8646722842745617323L; - - private final HttpResponse response; - - public TunnelRefusedException(final String message, final HttpResponse response) { - super(message); - this.response = response; - } - - public HttpResponse getResponse() { - return this.response; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/package-info.java deleted file mode 100644 index c684583a..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/execchain/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * HTTP request execution chain APIs. - */ -package org.apache.http.impl.execchain; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/AbstractMessageParserHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/AbstractMessageParserHC4.java deleted file mode 100644 index ec8408a4..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/AbstractMessageParserHC4.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.http.Header; -import org.apache.http.HttpException; -import org.apache.http.HttpMessage; -import org.apache.http.MessageConstraintException; -import org.apache.http.ParseException; -import org.apache.http.ProtocolException; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.config.MessageConstraints; -import org.apache.http.io.HttpMessageParser; -import org.apache.http.io.SessionInputBuffer; -import org.apache.http.message.BasicLineParserHC4; -import org.apache.http.message.LineParser; -import org.apache.http.params.HttpParamConfig; -import org.apache.http.params.HttpParams; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * Abstract base class for HTTP message parsers that obtain input from - * an instance of {@link SessionInputBuffer}. - * - * @since 4.0 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe -public abstract class AbstractMessageParserHC4 implements HttpMessageParser { - - private static final int HEAD_LINE = 0; - private static final int HEADERS = 1; - - private final SessionInputBuffer sessionBuffer; - private final MessageConstraints messageConstraints; - private final List headerLines; - protected final LineParser lineParser; - - private int state; - private T message; - - /** - * Creates an instance of AbstractMessageParserHC4. - * - * @param buffer the session input buffer. - * @param parser the line parser. - * @param params HTTP parameters. - * - * @deprecated (4.3) use {@link AbstractMessageParserHC4#AbstractMessageParserHC4(SessionInputBuffer, - * LineParser, MessageConstraints)} - */ - @Deprecated - public AbstractMessageParserHC4( - final SessionInputBuffer buffer, - final LineParser parser, - final HttpParams params) { - super(); - Args.notNull(buffer, "Session input buffer"); - Args.notNull(params, "HTTP parameters"); - this.sessionBuffer = buffer; - this.messageConstraints = HttpParamConfig.getMessageConstraints(params); - this.lineParser = (parser != null) ? parser : BasicLineParserHC4.INSTANCE; - this.headerLines = new ArrayList(); - this.state = HEAD_LINE; - } - - /** - * Creates new instance of AbstractMessageParserHC4. - * - * @param buffer the session input buffer. - * @param lineParser the line parser. If null {@link BasicLineParserHC4#INSTANCE} - * will be used. - * @param constraints the message constraints. If null - * {@link MessageConstraints#DEFAULT} will be used. - * - * @since 4.3 - */ - public AbstractMessageParserHC4( - final SessionInputBuffer buffer, - final LineParser lineParser, - final MessageConstraints constraints) { - super(); - this.sessionBuffer = Args.notNull(buffer, "Session input buffer"); - this.lineParser = lineParser != null ? lineParser : BasicLineParserHC4.INSTANCE; - this.messageConstraints = constraints != null ? constraints : MessageConstraints.DEFAULT; - this.headerLines = new ArrayList(); - this.state = HEAD_LINE; - } - - /** - * Parses HTTP headers from the data receiver stream according to the generic - * format as given in Section 3.1 of RFC 822, RFC-2616 Section 4 and 19.3. - * - * @param inbuffer Session input buffer - * @param maxHeaderCount maximum number of headers allowed. If the number - * of headers received from the data stream exceeds maxCount value, an - * IOException will be thrown. Setting this parameter to a negative value - * or zero will disable the check. - * @param maxLineLen maximum number of characters for a header line, - * including the continuation lines. Setting this parameter to a negative - * value or zero will disable the check. - * @return array of HTTP headers - * @param parser line parser to use. Can be null, in which case - * the default implementation of this interface will be used. - * - * @throws IOException in case of an I/O error - * @throws HttpException in case of HTTP protocol violation - */ - public static Header[] parseHeaders( - final SessionInputBuffer inbuffer, - final int maxHeaderCount, - final int maxLineLen, - final LineParser parser) throws HttpException, IOException { - final List headerLines = new ArrayList(); - return parseHeaders(inbuffer, maxHeaderCount, maxLineLen, - parser != null ? parser : BasicLineParserHC4.INSTANCE, - headerLines); - } - - /** - * Parses HTTP headers from the data receiver stream according to the generic - * format as given in Section 3.1 of RFC 822, RFC-2616 Section 4 and 19.3. - * - * @param inbuffer Session input buffer - * @param maxHeaderCount maximum number of headers allowed. If the number - * of headers received from the data stream exceeds maxCount value, an - * IOException will be thrown. Setting this parameter to a negative value - * or zero will disable the check. - * @param maxLineLen maximum number of characters for a header line, - * including the continuation lines. Setting this parameter to a negative - * value or zero will disable the check. - * @param parser line parser to use. - * @param headerLines List of header lines. This list will be used to store - * intermediate results. This makes it possible to resume parsing of - * headers in case of a {@link java.io.InterruptedIOException}. - * - * @return array of HTTP headers - * - * @throws IOException in case of an I/O error - * @throws HttpException in case of HTTP protocol violation - * - * @since 4.1 - */ - public static Header[] parseHeaders( - final SessionInputBuffer inbuffer, - final int maxHeaderCount, - final int maxLineLen, - final LineParser parser, - final List headerLines) throws HttpException, IOException { - Args.notNull(inbuffer, "Session input buffer"); - Args.notNull(parser, "Line parser"); - Args.notNull(headerLines, "Header line list"); - - CharArrayBuffer current = null; - CharArrayBuffer previous = null; - for (;;) { - if (current == null) { - current = new CharArrayBuffer(64); - } else { - current.clear(); - } - final int l = inbuffer.readLine(current); - if (l == -1 || current.length() < 1) { - break; - } - // Parse the header name and value - // Check for folded headers first - // Detect LWS-char see HTTP/1.0 or HTTP/1.1 Section 2.2 - // discussion on folded headers - if ((current.charAt(0) == ' ' || current.charAt(0) == '\t') && previous != null) { - // we have continuation folded header - // so append value - int i = 0; - while (i < current.length()) { - final char ch = current.charAt(i); - if (ch != ' ' && ch != '\t') { - break; - } - i++; - } - if (maxLineLen > 0 - && previous.length() + 1 + current.length() - i > maxLineLen) { - throw new MessageConstraintException("Maximum line length limit exceeded"); - } - previous.append(' '); - previous.append(current, i, current.length() - i); - } else { - headerLines.add(current); - previous = current; - current = null; - } - if (maxHeaderCount > 0 && headerLines.size() >= maxHeaderCount) { - throw new MessageConstraintException("Maximum header count exceeded"); - } - } - final Header[] headers = new Header[headerLines.size()]; - for (int i = 0; i < headerLines.size(); i++) { - final CharArrayBuffer buffer = headerLines.get(i); - try { - headers[i] = parser.parseHeader(buffer); - } catch (final ParseException ex) { - throw new ProtocolException(ex.getMessage()); - } - } - return headers; - } - - /** - * Subclasses must override this method to generate an instance of - * {@link HttpMessage} based on the initial input from the session buffer. - *

    - * Usually this method is expected to read just the very first line or - * the very first valid from the data stream and based on the input generate - * an appropriate instance of {@link HttpMessage}. - * - * @param sessionBuffer the session input buffer. - * @return HTTP message based on the input from the session buffer. - * @throws IOException in case of an I/O error. - * @throws HttpException in case of HTTP protocol violation. - * @throws ParseException in case of a parse error. - */ - protected abstract T parseHead(SessionInputBuffer sessionBuffer) - throws IOException, HttpException, ParseException; - - public T parse() throws IOException, HttpException { - final int st = this.state; - switch (st) { - case HEAD_LINE: - try { - this.message = parseHead(this.sessionBuffer); - } catch (final ParseException px) { - throw new ProtocolException(px.getMessage(), px); - } - this.state = HEADERS; - //$FALL-THROUGH$ - case HEADERS: - final Header[] headers = AbstractMessageParserHC4.parseHeaders( - this.sessionBuffer, - this.messageConstraints.getMaxHeaderCount(), - this.messageConstraints.getMaxLineLength(), - this.lineParser, - this.headerLines); - this.message.setHeaders(headers); - final T result = this.message; - this.message = null; - this.headerLines.clear(); - this.state = HEAD_LINE; - return result; - default: - throw new IllegalStateException("Inconsistent parser state"); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/AbstractMessageWriterHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/AbstractMessageWriterHC4.java deleted file mode 100644 index a821d2f5..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/AbstractMessageWriterHC4.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import java.io.IOException; - -import org.apache.http.Header; -import org.apache.http.HeaderIterator; -import org.apache.http.HttpException; -import org.apache.http.HttpMessage; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.io.HttpMessageWriter; -import org.apache.http.io.SessionOutputBuffer; -import org.apache.http.message.BasicLineFormatterHC4; -import org.apache.http.message.LineFormatter; -import org.apache.http.params.HttpParams; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * Abstract base class for HTTP message writers that serialize output to - * an instance of {@link SessionOutputBuffer}. - * - * @since 4.0 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe -public abstract class AbstractMessageWriterHC4 implements HttpMessageWriter { - - protected final SessionOutputBuffer sessionBuffer; - protected final CharArrayBuffer lineBuf; - protected final LineFormatter lineFormatter; - - /** - * Creates an instance of AbstractMessageWriterHC4. - * - * @param buffer the session output buffer. - * @param formatter the line formatter. - * @param params HTTP parameters. - * - * @deprecated (4.3) use - * {@link AbstractMessageWriterHC4#AbstractMessageWriterHC4(SessionOutputBuffer, LineFormatter)} - */ - @Deprecated - public AbstractMessageWriterHC4(final SessionOutputBuffer buffer, - final LineFormatter formatter, - final HttpParams params) { - super(); - Args.notNull(buffer, "Session input buffer"); - this.sessionBuffer = buffer; - this.lineBuf = new CharArrayBuffer(128); - this.lineFormatter = (formatter != null) ? formatter : BasicLineFormatterHC4.INSTANCE; - } - - /** - * Creates an instance of AbstractMessageWriterHC4. - * - * @param buffer the session output buffer. - * @param formatter the line formatter If null {@link BasicLineFormatterHC4#INSTANCE} - * will be used. - * - * @since 4.3 - */ - public AbstractMessageWriterHC4( - final SessionOutputBuffer buffer, - final LineFormatter formatter) { - super(); - this.sessionBuffer = Args.notNull(buffer, "Session input buffer"); - this.lineFormatter = (formatter != null) ? formatter : BasicLineFormatterHC4.INSTANCE; - this.lineBuf = new CharArrayBuffer(128); - } - - /** - * Subclasses must override this method to write out the first header line - * based on the {@link HttpMessage} passed as a parameter. - * - * @param message the message whose first line is to be written out. - * @throws IOException in case of an I/O error. - */ - protected abstract void writeHeadLine(HttpMessage message) throws IOException; - - public void write(final HttpMessage message) throws IOException, HttpException { - Args.notNull(message, "HTTP message"); - writeHeadLine(message); - for (final HeaderIterator it = message.headerIterator(); it.hasNext(); ) { - final Header header = it.nextHeader(); - this.sessionBuffer.writeLine - (lineFormatter.formatHeader(this.lineBuf, header)); - } - this.lineBuf.clear(); - this.sessionBuffer.writeLine(this.lineBuf); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/ChunkedInputStreamHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/ChunkedInputStreamHC4.java deleted file mode 100644 index 0d1a44b6..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/ChunkedInputStreamHC4.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.Header; -import org.apache.http.HttpException; -import org.apache.http.MalformedChunkCodingException; -import org.apache.http.TruncatedChunkException; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.io.BufferInfo; -import org.apache.http.io.SessionInputBuffer; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * Implements chunked transfer coding. The content is received in small chunks. - * Entities transferred using this input stream can be of unlimited length. - * After the stream is read to the end, it provides access to the trailers, - * if any. - *

    - * Note that this class NEVER closes the underlying stream, even when close - * gets called. Instead, it will read until the "end" of its chunking on - * close, which allows for the seamless execution of subsequent HTTP 1.1 - * requests, while not requiring the client to remember to read the entire - * contents of the response. - * - * - * @since 4.0 - * - */ -@NotThreadSafe -public class ChunkedInputStreamHC4 extends InputStream { - - private static final int CHUNK_LEN = 1; - private static final int CHUNK_DATA = 2; - private static final int CHUNK_CRLF = 3; - - private static final int BUFFER_SIZE = 2048; - - /** The session input buffer */ - private final SessionInputBuffer in; - - private final CharArrayBuffer buffer; - - private int state; - - /** The chunk size */ - private int chunkSize; - - /** The current position within the current chunk */ - private int pos; - - /** True if we've reached the end of stream */ - private boolean eof = false; - - /** True if this stream is closed */ - private boolean closed = false; - - private Header[] footers = new Header[] {}; - - /** - * Wraps session input stream and reads chunk coded input. - * - * @param in The session input buffer - */ - public ChunkedInputStreamHC4(final SessionInputBuffer in) { - super(); - this.in = Args.notNull(in, "Session input buffer"); - this.pos = 0; - this.buffer = new CharArrayBuffer(16); - this.state = CHUNK_LEN; - } - - @Override - public int available() throws IOException { - if (this.in instanceof BufferInfo) { - final int len = ((BufferInfo) this.in).length(); - return Math.min(len, this.chunkSize - this.pos); - } else { - return 0; - } - } - - /** - *

    Returns all the data in a chunked stream in coalesced form. A chunk - * is followed by a CRLF. The method returns -1 as soon as a chunksize of 0 - * is detected.

    - * - *

    Trailer headers are read automatically at the end of the stream and - * can be obtained with the getResponseFooters() method.

    - * - * @return -1 of the end of the stream has been reached or the next data - * byte - * @throws IOException in case of an I/O error - */ - @Override - public int read() throws IOException { - if (this.closed) { - throw new IOException("Attempted read from closed stream."); - } - if (this.eof) { - return -1; - } - if (state != CHUNK_DATA) { - nextChunk(); - if (this.eof) { - return -1; - } - } - final int b = in.read(); - if (b != -1) { - pos++; - if (pos >= chunkSize) { - state = CHUNK_CRLF; - } - } - return b; - } - - /** - * Read some bytes from the stream. - * @param b The byte array that will hold the contents from the stream. - * @param off The offset into the byte array at which bytes will start to be - * placed. - * @param len the maximum number of bytes that can be returned. - * @return The number of bytes returned or -1 if the end of stream has been - * reached. - * @throws IOException in case of an I/O error - */ - @Override - public int read (final byte[] b, final int off, final int len) throws IOException { - - if (closed) { - throw new IOException("Attempted read from closed stream."); - } - - if (eof) { - return -1; - } - if (state != CHUNK_DATA) { - nextChunk(); - if (eof) { - return -1; - } - } - final int bytesRead = in.read(b, off, Math.min(len, chunkSize - pos)); - if (bytesRead != -1) { - pos += bytesRead; - if (pos >= chunkSize) { - state = CHUNK_CRLF; - } - return bytesRead; - } else { - eof = true; - throw new TruncatedChunkException("Truncated chunk " - + "( expected size: " + chunkSize - + "; actual size: " + pos + ")"); - } - } - - /** - * Read some bytes from the stream. - * @param b The byte array that will hold the contents from the stream. - * @return The number of bytes returned or -1 if the end of stream has been - * reached. - * @throws IOException in case of an I/O error - */ - @Override - public int read (final byte[] b) throws IOException { - return read(b, 0, b.length); - } - - /** - * Read the next chunk. - * @throws IOException in case of an I/O error - */ - private void nextChunk() throws IOException { - chunkSize = getChunkSize(); - if (chunkSize < 0) { - throw new MalformedChunkCodingException("Negative chunk size"); - } - state = CHUNK_DATA; - pos = 0; - if (chunkSize == 0) { - eof = true; - parseTrailerHeaders(); - } - } - - /** - * Expects the stream to start with a chunksize in hex with optional - * comments after a semicolon. The line must end with a CRLF: "a3; some - * comment\r\n" Positions the stream at the start of the next line. - */ - private int getChunkSize() throws IOException { - final int st = this.state; - switch (st) { - case CHUNK_CRLF: - this.buffer.clear(); - final int bytesRead1 = this.in.readLine(this.buffer); - if (bytesRead1 == -1) { - return 0; - } - if (!this.buffer.isEmpty()) { - throw new MalformedChunkCodingException( - "Unexpected content at the end of chunk"); - } - state = CHUNK_LEN; - //$FALL-THROUGH$ - case CHUNK_LEN: - this.buffer.clear(); - final int bytesRead2 = this.in.readLine(this.buffer); - if (bytesRead2 == -1) { - return 0; - } - int separator = this.buffer.indexOf(';'); - if (separator < 0) { - separator = this.buffer.length(); - } - try { - return Integer.parseInt(this.buffer.substringTrimmed(0, separator), 16); - } catch (final NumberFormatException e) { - throw new MalformedChunkCodingException("Bad chunk header"); - } - default: - throw new IllegalStateException("Inconsistent codec state"); - } - } - - /** - * Reads and stores the Trailer headers. - * @throws IOException in case of an I/O error - */ - private void parseTrailerHeaders() throws IOException { - try { - this.footers = AbstractMessageParserHC4.parseHeaders - (in, -1, -1, null); - } catch (final HttpException ex) { - final IOException ioe = new MalformedChunkCodingException("Invalid footer: " - + ex.getMessage()); - ioe.initCause(ex); - throw ioe; - } - } - - /** - * Upon close, this reads the remainder of the chunked message, - * leaving the underlying socket at a position to start reading the - * next response without scanning. - * @throws IOException in case of an I/O error - */ - @Override - public void close() throws IOException { - if (!closed) { - try { - if (!eof) { - // read and discard the remainder of the message - final byte buff[] = new byte[BUFFER_SIZE]; - while (read(buff) >= 0) { - } - } - } finally { - eof = true; - closed = true; - } - } - } - - public Header[] getFooters() { - return this.footers.clone(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/ChunkedOutputStreamHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/ChunkedOutputStreamHC4.java deleted file mode 100644 index 00d489e2..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/ChunkedOutputStreamHC4.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.io.SessionOutputBuffer; - -/** - * Implements chunked transfer coding. The content is sent in small chunks. - * Entities transferred using this output stream can be of unlimited length. - * Writes are buffered to an internal buffer (2048 default size). - *

    - * Note that this class NEVER closes the underlying stream, even when close - * gets called. Instead, the stream will be marked as closed and no further - * output will be permitted. - * - * - * @since 4.0 - */ -@NotThreadSafe -public class ChunkedOutputStreamHC4 extends OutputStream { - - // ----------------------------------------------------- Instance Variables - private final SessionOutputBuffer out; - - private final byte[] cache; - - private int cachePosition = 0; - - private boolean wroteLastChunk = false; - - /** True if the stream is closed. */ - private boolean closed = false; - - /** - * Wraps a session output buffer and chunk-encodes the output. - * - * @param out The session output buffer - * @param bufferSize The minimum chunk size (excluding last chunk) - * @throws IOException not thrown - * - * @deprecated (4.3) use {@link ChunkedOutputStreamHC4#ChunkedOutputStreamHC4(int, SessionOutputBuffer)} - */ - @Deprecated - public ChunkedOutputStreamHC4(final SessionOutputBuffer out, final int bufferSize) - throws IOException { - this(bufferSize, out); - } - - /** - * Wraps a session output buffer and chunks the output. The default buffer - * size of 2048 was chosen because the chunk overhead is less than 0.5% - * - * @param out the output buffer to wrap - * @throws IOException not thrown - * - * @deprecated (4.3) use {@link ChunkedOutputStreamHC4#ChunkedOutputStreamHC4(int, SessionOutputBuffer)} - */ - @Deprecated - public ChunkedOutputStreamHC4(final SessionOutputBuffer out) - throws IOException { - this(2048, out); - } - - /** - * Wraps a session output buffer and chunk-encodes the output. - * - * @param bufferSize The minimum chunk size (excluding last chunk) - * @param out The session output buffer - */ - public ChunkedOutputStreamHC4(final int bufferSize, final SessionOutputBuffer out) { - super(); - this.cache = new byte[bufferSize]; - this.out = out; - } - - /** - * Writes the cache out onto the underlying stream - */ - protected void flushCache() throws IOException { - if (this.cachePosition > 0) { - this.out.writeLine(Integer.toHexString(this.cachePosition)); - this.out.write(this.cache, 0, this.cachePosition); - this.out.writeLine(""); - this.cachePosition = 0; - } - } - - /** - * Writes the cache and bufferToAppend to the underlying stream - * as one large chunk - */ - protected void flushCacheWithAppend(final byte bufferToAppend[], final int off, final int len) throws IOException { - this.out.writeLine(Integer.toHexString(this.cachePosition + len)); - this.out.write(this.cache, 0, this.cachePosition); - this.out.write(bufferToAppend, off, len); - this.out.writeLine(""); - this.cachePosition = 0; - } - - protected void writeClosingChunk() throws IOException { - // Write the final chunk. - this.out.writeLine("0"); - this.out.writeLine(""); - } - - // ----------------------------------------------------------- Public Methods - /** - * Must be called to ensure the internal cache is flushed and the closing - * chunk is written. - * @throws IOException in case of an I/O error - */ - public void finish() throws IOException { - if (!this.wroteLastChunk) { - flushCache(); - writeClosingChunk(); - this.wroteLastChunk = true; - } - } - - // -------------------------------------------- OutputStream Methods - @Override - public void write(final int b) throws IOException { - if (this.closed) { - throw new IOException("Attempted write to closed stream."); - } - this.cache[this.cachePosition] = (byte) b; - this.cachePosition++; - if (this.cachePosition == this.cache.length) { - flushCache(); - } - } - - /** - * Writes the array. If the array does not fit within the buffer, it is - * not split, but rather written out as one large chunk. - */ - @Override - public void write(final byte b[]) throws IOException { - write(b, 0, b.length); - } - - /** - * Writes the array. If the array does not fit within the buffer, it is - * not split, but rather written out as one large chunk. - */ - @Override - public void write(final byte src[], final int off, final int len) throws IOException { - if (this.closed) { - throw new IOException("Attempted write to closed stream."); - } - if (len >= this.cache.length - this.cachePosition) { - flushCacheWithAppend(src, off, len); - } else { - System.arraycopy(src, off, cache, this.cachePosition, len); - this.cachePosition += len; - } - } - - /** - * Flushes the content buffer and the underlying stream. - */ - @Override - public void flush() throws IOException { - flushCache(); - this.out.flush(); - } - - /** - * Finishes writing to the underlying stream, but does NOT close the underlying stream. - */ - @Override - public void close() throws IOException { - if (!this.closed) { - this.closed = true; - finish(); - this.out.flush(); - } - } -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/ContentLengthInputStreamHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/ContentLengthInputStreamHC4.java deleted file mode 100644 index 476f57a7..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/ContentLengthInputStreamHC4.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.ConnectionClosedException; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.io.BufferInfo; -import org.apache.http.io.SessionInputBuffer; -import org.apache.http.util.Args; - -/** - * Input stream that cuts off after a defined number of bytes. This class - * is used to receive content of HTTP messages where the end of the content - * entity is determined by the value of the Content-Length header. - * Entities transferred using this stream can be maximum {@link Long#MAX_VALUE} - * long. - *

    - * Note that this class NEVER closes the underlying stream, even when close - * gets called. Instead, it will read until the "end" of its limit on - * close, which allows for the seamless execution of subsequent HTTP 1.1 - * requests, while not requiring the client to remember to read the entire - * contents of the response. - * - * - * @since 4.0 - */ -@NotThreadSafe -public class ContentLengthInputStreamHC4 extends InputStream { - - private static final int BUFFER_SIZE = 2048; - /** - * The maximum number of bytes that can be read from the stream. Subsequent - * read operations will return -1. - */ - private final long contentLength; - - /** The current position */ - private long pos = 0; - - /** True if the stream is closed. */ - private boolean closed = false; - - /** - * Wrapped input stream that all calls are delegated to. - */ - private SessionInputBuffer in = null; - - /** - * Wraps a session input buffer and cuts off output after a defined number - * of bytes. - * - * @param in The session input buffer - * @param contentLength The maximum number of bytes that can be read from - * the stream. Subsequent read operations will return -1. - */ - public ContentLengthInputStreamHC4(final SessionInputBuffer in, final long contentLength) { - super(); - this.in = Args.notNull(in, "Session input buffer"); - this.contentLength = Args.notNegative(contentLength, "Content length"); - } - - /** - *

    Reads until the end of the known length of content.

    - * - *

    Does not close the underlying socket input, but instead leaves it - * primed to parse the next response.

    - * @throws IOException If an IO problem occurs. - */ - @Override - public void close() throws IOException { - if (!closed) { - try { - if (pos < contentLength) { - final byte buffer[] = new byte[BUFFER_SIZE]; - while (read(buffer) >= 0) { - } - } - } finally { - // close after above so that we don't throw an exception trying - // to read after closed! - closed = true; - } - } - } - - @Override - public int available() throws IOException { - if (this.in instanceof BufferInfo) { - final int len = ((BufferInfo) this.in).length(); - return Math.min(len, (int) (this.contentLength - this.pos)); - } else { - return 0; - } - } - - /** - * Read the next byte from the stream - * @return The next byte or -1 if the end of stream has been reached. - * @throws IOException If an IO problem occurs - * @see java.io.InputStream#read() - */ - @Override - public int read() throws IOException { - if (closed) { - throw new IOException("Attempted read from closed stream."); - } - - if (pos >= contentLength) { - return -1; - } - final int b = this.in.read(); - if (b == -1) { - if (pos < contentLength) { - throw new ConnectionClosedException( - "Premature end of Content-Length delimited message body (expected: " - + contentLength + "; received: " + pos); - } - } else { - pos++; - } - return b; - } - - /** - * Does standard {@link InputStream#read(byte[], int, int)} behavior, but - * also notifies the watcher when the contents have been consumed. - * - * @param b The byte array to fill. - * @param off Start filling at this position. - * @param len The number of bytes to attempt to read. - * @return The number of bytes read, or -1 if the end of content has been - * reached. - * - * @throws java.io.IOException Should an error occur on the wrapped stream. - */ - @Override - public int read (final byte[] b, final int off, final int len) throws java.io.IOException { - if (closed) { - throw new IOException("Attempted read from closed stream."); - } - - if (pos >= contentLength) { - return -1; - } - - int chunk = len; - if (pos + len > contentLength) { - chunk = (int) (contentLength - pos); - } - final int count = this.in.read(b, off, chunk); - if (count == -1 && pos < contentLength) { - throw new ConnectionClosedException( - "Premature end of Content-Length delimited message body (expected: " - + contentLength + "; received: " + pos); - } - if (count > 0) { - pos += count; - } - return count; - } - - - /** - * Read more bytes from the stream. - * @param b The byte array to put the new data in. - * @return The number of bytes read into the buffer. - * @throws IOException If an IO problem occurs - * @see java.io.InputStream#read(byte[]) - */ - @Override - public int read(final byte[] b) throws IOException { - return read(b, 0, b.length); - } - - /** - * Skips and discards a number of bytes from the input stream. - * @param n The number of bytes to skip. - * @return The actual number of bytes skipped. <= 0 if no bytes - * are skipped. - * @throws IOException If an error occurs while skipping bytes. - * @see InputStream#skip(long) - */ - @Override - public long skip(final long n) throws IOException { - if (n <= 0) { - return 0; - } - final byte[] buffer = new byte[BUFFER_SIZE]; - // make sure we don't skip more bytes than are - // still available - long remaining = Math.min(n, this.contentLength - this.pos); - // skip and keep track of the bytes actually skipped - long count = 0; - while (remaining > 0) { - final int l = read(buffer, 0, (int)Math.min(BUFFER_SIZE, remaining)); - if (l == -1) { - break; - } - count += l; - remaining -= l; - } - return count; - } -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/ContentLengthOutputStreamHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/ContentLengthOutputStreamHC4.java deleted file mode 100644 index 815b540f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/ContentLengthOutputStreamHC4.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.io.SessionOutputBuffer; -import org.apache.http.util.Args; - -/** - * Output stream that cuts off after a defined number of bytes. This class - * is used to send content of HTTP messages where the end of the content entity - * is determined by the value of the Content-Length header. - * Entities transferred using this stream can be maximum {@link Long#MAX_VALUE} - * long. - *

    - * Note that this class NEVER closes the underlying stream, even when close - * gets called. Instead, the stream will be marked as closed and no further - * output will be permitted. - * - * @since 4.0 - */ -@NotThreadSafe -public class ContentLengthOutputStreamHC4 extends OutputStream { - - /** - * Wrapped session output buffer. - */ - private final SessionOutputBuffer out; - - /** - * The maximum number of bytes that can be written the stream. Subsequent - * write operations will be ignored. - */ - private final long contentLength; - - /** Total bytes written */ - private long total = 0; - - /** True if the stream is closed. */ - private boolean closed = false; - - /** - * Wraps a session output buffer and cuts off output after a defined number - * of bytes. - * - * @param out The session output buffer - * @param contentLength The maximum number of bytes that can be written to - * the stream. Subsequent write operations will be ignored. - * - * @since 4.0 - */ - public ContentLengthOutputStreamHC4(final SessionOutputBuffer out, final long contentLength) { - super(); - this.out = Args.notNull(out, "Session output buffer"); - this.contentLength = Args.notNegative(contentLength, "Content length"); - } - - /** - *

    Does not close the underlying socket output.

    - * - * @throws IOException If an I/O problem occurs. - */ - @Override - public void close() throws IOException { - if (!this.closed) { - this.closed = true; - this.out.flush(); - } - } - - @Override - public void flush() throws IOException { - this.out.flush(); - } - - @Override - public void write(final byte[] b, final int off, final int len) throws IOException { - if (this.closed) { - throw new IOException("Attempted write to closed stream."); - } - if (this.total < this.contentLength) { - final long max = this.contentLength - this.total; - int chunk = len; - if (chunk > max) { - chunk = (int) max; - } - this.out.write(b, off, chunk); - this.total += chunk; - } - } - - @Override - public void write(final byte[] b) throws IOException { - write(b, 0, b.length); - } - - @Override - public void write(final int b) throws IOException { - if (this.closed) { - throw new IOException("Attempted write to closed stream."); - } - if (this.total < this.contentLength) { - this.out.write(b); - this.total++; - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpRequestParser.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpRequestParser.java deleted file mode 100644 index bb7473a1..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpRequestParser.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import java.io.IOException; - -import org.apache.http.ConnectionClosedException; -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestFactory; -import org.apache.http.ParseException; -import org.apache.http.RequestLine; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.config.MessageConstraints; -import org.apache.http.impl.DefaultHttpRequestFactoryHC4; -import org.apache.http.io.SessionInputBuffer; -import org.apache.http.message.LineParser; -import org.apache.http.message.ParserCursor; -import org.apache.http.params.HttpParams; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * HTTP request parser that obtain its input from an instance - * of {@link SessionInputBuffer}. - * - * @since 4.2 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe -public class DefaultHttpRequestParser extends AbstractMessageParserHC4 { - - private final HttpRequestFactory requestFactory; - private final CharArrayBuffer lineBuf; - - /** - * Creates an instance of this class. - * - * @param buffer the session input buffer. - * @param lineParser the line parser. - * @param requestFactory the factory to use to create - * {@link HttpRequest}s. - * @param params HTTP parameters. - * - * @deprecated (4.3) use - * {@link DefaultHttpRequestParser#DefaultHttpRequestParser(SessionInputBuffer, LineParser, - * HttpRequestFactory, MessageConstraints)} - */ - @Deprecated - public DefaultHttpRequestParser( - final SessionInputBuffer buffer, - final LineParser lineParser, - final HttpRequestFactory requestFactory, - final HttpParams params) { - super(buffer, lineParser, params); - this.requestFactory = Args.notNull(requestFactory, "Request factory"); - this.lineBuf = new CharArrayBuffer(128); - } - - /** - * Creates new instance of DefaultHttpRequestParser. - * - * @param buffer the session input buffer. - * @param lineParser the line parser. If null - * {@link org.apache.http.message.BasicLineParserHC4#INSTANCE} will be used. - * @param requestFactory the response factory. If null - * {@link DefaultHttpRequestFactoryHC4#INSTANCE} will be used. - * @param constraints the message constraints. If null - * {@link MessageConstraints#DEFAULT} will be used. - * - * @since 4.3 - */ - public DefaultHttpRequestParser( - final SessionInputBuffer buffer, - final LineParser lineParser, - final HttpRequestFactory requestFactory, - final MessageConstraints constraints) { - super(buffer, lineParser, constraints); - this.requestFactory = requestFactory != null ? requestFactory : - DefaultHttpRequestFactoryHC4.INSTANCE; - this.lineBuf = new CharArrayBuffer(128); - } - - /** - * @since 4.3 - */ - public DefaultHttpRequestParser( - final SessionInputBuffer buffer, - final MessageConstraints constraints) { - this(buffer, null, null, constraints); - } - - /** - * @since 4.3 - */ - public DefaultHttpRequestParser(final SessionInputBuffer buffer) { - this(buffer, null, null, MessageConstraints.DEFAULT); - } - - @Override - protected HttpRequest parseHead( - final SessionInputBuffer sessionBuffer) - throws IOException, HttpException, ParseException { - - this.lineBuf.clear(); - final int i = sessionBuffer.readLine(this.lineBuf); - if (i == -1) { - throw new ConnectionClosedException("Client closed connection"); - } - final ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); - final RequestLine requestline = this.lineParser.parseRequestLine(this.lineBuf, cursor); - return this.requestFactory.newHttpRequest(requestline); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpRequestParserFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpRequestParserFactory.java deleted file mode 100644 index 8a4e4bb2..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpRequestParserFactory.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestFactory; -import org.apache.http.annotation.Immutable; -import org.apache.http.config.MessageConstraints; -import org.apache.http.impl.DefaultHttpRequestFactoryHC4; -import org.apache.http.io.HttpMessageParser; -import org.apache.http.io.HttpMessageParserFactory; -import org.apache.http.io.SessionInputBuffer; -import org.apache.http.message.BasicLineParserHC4; -import org.apache.http.message.LineParser; - -/** - * Default factory for request message parsers. - * - * @since 4.3 - */ -@Immutable -public class DefaultHttpRequestParserFactory implements HttpMessageParserFactory { - - public static final DefaultHttpRequestParserFactory INSTANCE = new DefaultHttpRequestParserFactory(); - - private final LineParser lineParser; - private final HttpRequestFactory requestFactory; - - public DefaultHttpRequestParserFactory(final LineParser lineParser, - final HttpRequestFactory requestFactory) { - super(); - this.lineParser = lineParser != null ? lineParser : BasicLineParserHC4.INSTANCE; - this.requestFactory = requestFactory != null ? requestFactory - : DefaultHttpRequestFactoryHC4.INSTANCE; - } - - public DefaultHttpRequestParserFactory() { - this(null, null); - } - - public HttpMessageParser create(final SessionInputBuffer buffer, - final MessageConstraints constraints) { - return new DefaultHttpRequestParser(buffer, lineParser, requestFactory, constraints); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpRequestWriter.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpRequestWriter.java deleted file mode 100644 index 7654fa14..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpRequestWriter.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import java.io.IOException; - -import org.apache.http.HttpMessage; -import org.apache.http.HttpRequest; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.io.SessionOutputBuffer; -import org.apache.http.message.LineFormatter; - -/** - * HTTP request writer that serializes its output to an instance of {@link SessionOutputBuffer}. - * - * @since 4.3 - */ -@NotThreadSafe -public class DefaultHttpRequestWriter extends AbstractMessageWriterHC4 { - - /** - * Creates an instance of DefaultHttpRequestWriter. - * - * @param buffer the session output buffer. - * @param formatter the line formatter If null - * {@link org.apache.http.message.BasicLineFormatterHC4#INSTANCE} - * will be used. - */ - public DefaultHttpRequestWriter( - final SessionOutputBuffer buffer, - final LineFormatter formatter) { - super(buffer, formatter); - } - - public DefaultHttpRequestWriter(final SessionOutputBuffer buffer) { - this(buffer, null); - } - - @Override - protected void writeHeadLine(final HttpMessage message) throws IOException { - lineFormatter.formatRequestLine(this.lineBuf, ((HttpRequest) message).getRequestLine()); - this.sessionBuffer.writeLine(this.lineBuf); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpRequestWriterFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpRequestWriterFactory.java deleted file mode 100644 index 2ca51b9d..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpRequestWriterFactory.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import org.apache.http.HttpRequest; -import org.apache.http.annotation.Immutable; -import org.apache.http.io.HttpMessageWriter; -import org.apache.http.io.HttpMessageWriterFactory; -import org.apache.http.io.SessionOutputBuffer; -import org.apache.http.message.BasicLineFormatterHC4; -import org.apache.http.message.LineFormatter; - -/** - * Default factory for request message writers. - * - * @since 4.3 - */ -@Immutable -public class DefaultHttpRequestWriterFactory implements HttpMessageWriterFactory { - - public static final DefaultHttpRequestWriterFactory INSTANCE = new DefaultHttpRequestWriterFactory(); - - private final LineFormatter lineFormatter; - - public DefaultHttpRequestWriterFactory(final LineFormatter lineFormatter) { - super(); - this.lineFormatter = lineFormatter != null ? lineFormatter : BasicLineFormatterHC4.INSTANCE; - } - - public DefaultHttpRequestWriterFactory() { - this(null); - } - - public HttpMessageWriter create(final SessionOutputBuffer buffer) { - return new DefaultHttpRequestWriter(buffer, lineFormatter); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpResponseParser.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpResponseParser.java deleted file mode 100644 index 477e4944..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpResponseParser.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import java.io.IOException; - -import org.apache.http.HttpException; -import org.apache.http.HttpResponse; -import org.apache.http.HttpResponseFactory; -import org.apache.http.NoHttpResponseException; -import org.apache.http.ParseException; -import org.apache.http.StatusLine; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.config.MessageConstraints; -import org.apache.http.impl.DefaultHttpResponseFactoryHC4; -import org.apache.http.io.SessionInputBuffer; -import org.apache.http.message.LineParser; -import org.apache.http.message.ParserCursor; -import org.apache.http.params.HttpParams; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * HTTP response parser that obtain its input from an instance - * of {@link SessionInputBuffer}. - * - * @since 4.2 - */ -@SuppressWarnings("deprecation") -@NotThreadSafe -public class DefaultHttpResponseParser extends AbstractMessageParserHC4 { - - private final HttpResponseFactory responseFactory; - private final CharArrayBuffer lineBuf; - - /** - * Creates an instance of this class. - * - * @param buffer the session input buffer. - * @param lineParser the line parser. - * @param responseFactory the factory to use to create - * {@link HttpResponse}s. - * @param params HTTP parameters. - * - * @deprecated (4.3) use - * {@link DefaultHttpResponseParser#DefaultHttpResponseParser(SessionInputBuffer, LineParser, - * HttpResponseFactory, MessageConstraints)} - */ - @Deprecated - public DefaultHttpResponseParser( - final SessionInputBuffer buffer, - final LineParser lineParser, - final HttpResponseFactory responseFactory, - final HttpParams params) { - super(buffer, lineParser, params); - this.responseFactory = Args.notNull(responseFactory, "Response factory"); - this.lineBuf = new CharArrayBuffer(128); - } - - /** - * Creates new instance of DefaultHttpResponseParser. - * - * @param buffer the session input buffer. - * @param lineParser the line parser. If null - * {@link org.apache.http.message.BasicLineParserHC4#INSTANCE} will be used - * @param responseFactory the response factory. If null - * {@link DefaultHttpResponseFactoryHC4#INSTANCE} will be used. - * @param constraints the message constraints. If null - * {@link MessageConstraints#DEFAULT} will be used. - * - * @since 4.3 - */ - public DefaultHttpResponseParser( - final SessionInputBuffer buffer, - final LineParser lineParser, - final HttpResponseFactory responseFactory, - final MessageConstraints constraints) { - super(buffer, lineParser, constraints); - this.responseFactory = responseFactory != null ? responseFactory : - DefaultHttpResponseFactoryHC4.INSTANCE; - this.lineBuf = new CharArrayBuffer(128); - } - - /** - * @since 4.3 - */ - public DefaultHttpResponseParser( - final SessionInputBuffer buffer, - final MessageConstraints constraints) { - this(buffer, null, null, constraints); - } - - /** - * @since 4.3 - */ - public DefaultHttpResponseParser(final SessionInputBuffer buffer) { - this(buffer, null, null, MessageConstraints.DEFAULT); - } - - @Override - protected HttpResponse parseHead( - final SessionInputBuffer sessionBuffer) - throws IOException, HttpException, ParseException { - - this.lineBuf.clear(); - final int i = sessionBuffer.readLine(this.lineBuf); - if (i == -1) { - throw new NoHttpResponseException("The target server failed to respond"); - } - //create the status line from the status string - final ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); - final StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, cursor); - return this.responseFactory.newHttpResponse(statusline, null); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpResponseParserFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpResponseParserFactory.java deleted file mode 100644 index 5e7b9b2d..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpResponseParserFactory.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import org.apache.http.HttpResponse; -import org.apache.http.HttpResponseFactory; -import org.apache.http.annotation.Immutable; -import org.apache.http.config.MessageConstraints; -import org.apache.http.impl.DefaultHttpResponseFactoryHC4; -import org.apache.http.io.HttpMessageParser; -import org.apache.http.io.HttpMessageParserFactory; -import org.apache.http.io.SessionInputBuffer; -import org.apache.http.message.BasicLineParserHC4; -import org.apache.http.message.LineParser; - -/** - * Default factory for response message parsers. - * - * @since 4.3 - */ -@Immutable -public class DefaultHttpResponseParserFactory implements HttpMessageParserFactory { - - public static final DefaultHttpResponseParserFactory INSTANCE = new DefaultHttpResponseParserFactory(); - - private final LineParser lineParser; - private final HttpResponseFactory responseFactory; - - public DefaultHttpResponseParserFactory(final LineParser lineParser, - final HttpResponseFactory responseFactory) { - super(); - this.lineParser = lineParser != null ? lineParser : BasicLineParserHC4.INSTANCE; - this.responseFactory = responseFactory != null ? responseFactory - : DefaultHttpResponseFactoryHC4.INSTANCE; - } - - public DefaultHttpResponseParserFactory() { - this(null, null); - } - - public HttpMessageParser create(final SessionInputBuffer buffer, - final MessageConstraints constraints) { - return new DefaultHttpResponseParser(buffer, lineParser, responseFactory, constraints); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpResponseWriter.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpResponseWriter.java deleted file mode 100644 index 894c8d88..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpResponseWriter.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import java.io.IOException; - -import org.apache.http.HttpMessage; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.io.SessionOutputBuffer; -import org.apache.http.message.LineFormatter; - -/** - * HTTP response writer that serializes its output to an instance of {@link SessionOutputBuffer}. - * - * @since 4.3 - */ -@NotThreadSafe -public class DefaultHttpResponseWriter extends AbstractMessageWriterHC4 { - - /** - * Creates an instance of DefaultHttpResponseWriter. - * - * @param buffer the session output buffer. - * @param formatter the line formatter If null - * {@link org.apache.http.message.BasicLineFormatterHC4#INSTANCE} - * will be used. - */ - public DefaultHttpResponseWriter( - final SessionOutputBuffer buffer, - final LineFormatter formatter) { - super(buffer, formatter); - } - - public DefaultHttpResponseWriter(final SessionOutputBuffer buffer) { - super(buffer, null); - } - - @Override - protected void writeHeadLine(final HttpMessage message) throws IOException { - lineFormatter.formatStatusLine(this.lineBuf, ((HttpResponse) message).getStatusLine()); - this.sessionBuffer.writeLine(this.lineBuf); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpResponseWriterFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpResponseWriterFactory.java deleted file mode 100644 index 8c07d445..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/DefaultHttpResponseWriterFactory.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import org.apache.http.HttpResponse; -import org.apache.http.annotation.Immutable; -import org.apache.http.io.HttpMessageWriter; -import org.apache.http.io.HttpMessageWriterFactory; -import org.apache.http.io.SessionOutputBuffer; -import org.apache.http.message.BasicLineFormatterHC4; -import org.apache.http.message.LineFormatter; - -/** - * Default factory for response message writers. - * - * @since 4.3 - */ -@Immutable -public class DefaultHttpResponseWriterFactory implements HttpMessageWriterFactory { - - public static final DefaultHttpResponseWriterFactory INSTANCE = new DefaultHttpResponseWriterFactory(); - - private final LineFormatter lineFormatter; - - public DefaultHttpResponseWriterFactory(final LineFormatter lineFormatter) { - super(); - this.lineFormatter = lineFormatter != null ? lineFormatter : BasicLineFormatterHC4.INSTANCE; - } - - public DefaultHttpResponseWriterFactory() { - this(null); - } - - public HttpMessageWriter create(final SessionOutputBuffer buffer) { - return new DefaultHttpResponseWriter(buffer, lineFormatter); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/IdentityInputStreamHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/IdentityInputStreamHC4.java deleted file mode 100644 index 550a0e12..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/IdentityInputStreamHC4.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.io.BufferInfo; -import org.apache.http.io.SessionInputBuffer; -import org.apache.http.util.Args; - -/** - * Input stream that reads data without any transformation. The end of the - * content entity is demarcated by closing the underlying connection - * (EOF condition). Entities transferred using this input stream can be of - * unlimited length. - *

    - * Note that this class NEVER closes the underlying stream, even when close - * gets called. Instead, it will read until the end of the stream (until - * -1 is returned). - * - * @since 4.0 - */ -@NotThreadSafe -public class IdentityInputStreamHC4 extends InputStream { - - private final SessionInputBuffer in; - - private boolean closed = false; - - /** - * Wraps session input stream and reads input until the the end of stream. - * - * @param in The session input buffer - */ - public IdentityInputStreamHC4(final SessionInputBuffer in) { - super(); - this.in = Args.notNull(in, "Session input buffer"); - } - - @Override - public int available() throws IOException { - if (this.in instanceof BufferInfo) { - return ((BufferInfo) this.in).length(); - } else { - return 0; - } - } - - @Override - public void close() throws IOException { - this.closed = true; - } - - @Override - public int read() throws IOException { - if (this.closed) { - return -1; - } else { - return this.in.read(); - } - } - - @Override - public int read(final byte[] b, final int off, final int len) throws IOException { - if (this.closed) { - return -1; - } else { - return this.in.read(b, off, len); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/IdentityOutputStreamHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/IdentityOutputStreamHC4.java deleted file mode 100644 index 8305d59e..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/IdentityOutputStreamHC4.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.io.SessionOutputBuffer; -import org.apache.http.util.Args; - -/** - * Output stream that writes data without any transformation. The end of - * the content entity is demarcated by closing the underlying connection - * (EOF condition). Entities transferred using this input stream can be of - * unlimited length. - *

    - * Note that this class NEVER closes the underlying stream, even when close - * gets called. Instead, the stream will be marked as closed and no further - * output will be permitted. - * - * @since 4.0 - */ -@NotThreadSafe -public class IdentityOutputStreamHC4 extends OutputStream { - - /** - * Wrapped session output buffer. - */ - private final SessionOutputBuffer out; - - /** True if the stream is closed. */ - private boolean closed = false; - - public IdentityOutputStreamHC4(final SessionOutputBuffer out) { - super(); - this.out = Args.notNull(out, "Session output buffer"); - } - - /** - *

    Does not close the underlying socket output.

    - * - * @throws IOException If an I/O problem occurs. - */ - @Override - public void close() throws IOException { - if (!this.closed) { - this.closed = true; - this.out.flush(); - } - } - - @Override - public void flush() throws IOException { - this.out.flush(); - } - - @Override - public void write(final byte[] b, final int off, final int len) throws IOException { - if (this.closed) { - throw new IOException("Attempted write to closed stream."); - } - this.out.write(b, off, len); - } - - @Override - public void write(final byte[] b) throws IOException { - write(b, 0, b.length); - } - - @Override - public void write(final int b) throws IOException { - if (this.closed) { - throw new IOException("Attempted write to closed stream."); - } - this.out.write(b); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/SessionInputBufferImpl.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/SessionInputBufferImpl.java deleted file mode 100644 index 801c2219..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/SessionInputBufferImpl.java +++ /dev/null @@ -1,399 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CoderResult; - -import org.apache.http.MessageConstraintException; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.config.MessageConstraints; -import org.apache.http.io.BufferInfo; -import org.apache.http.io.HttpTransportMetrics; -import org.apache.http.io.SessionInputBuffer; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.Args; -import org.apache.http.util.Asserts; -import org.apache.http.util.ByteArrayBuffer; -import org.apache.http.util.CharArrayBuffer; - -/** - * Abstract base class for session input buffers that stream data from - * an arbitrary {@link InputStream}. This class buffers input data in - * an internal byte array for optimal input performance. - *

    - * {@link #readLine(CharArrayBuffer)} and {@link #readLine()} methods of this - * class treat a lone LF as valid line delimiters in addition to CR-LF required - * by the HTTP specification. - * - * @since 4.3 - */ -@NotThreadSafe -public class SessionInputBufferImpl implements SessionInputBuffer, BufferInfo { - - private final HttpTransportMetricsImpl metrics; - private final byte[] buffer; - private final ByteArrayBuffer linebuffer; - private final int minChunkLimit; - private final MessageConstraints constraints; - private final CharsetDecoder decoder; - - private InputStream instream; - private int bufferpos; - private int bufferlen; - private CharBuffer cbuf; - - /** - * Creates new instance of SessionInputBufferImpl. - * - * @param metrics HTTP transport metrics. - * @param buffersize buffer size. Must be a positive number. - * @param minChunkLimit size limit below which data chunks should be buffered in memory - * in order to minimize native method invocations on the underlying network socket. - * The optimal value of this parameter can be platform specific and defines a trade-off - * between performance of memory copy operations and that of native method invocation. - * If negative default chunk limited will be used. - * @param constraints Message constraints. If null - * {@link MessageConstraints#DEFAULT} will be used. - * @param chardecoder chardecoder to be used for decoding HTTP protocol elements. - * If null simple type cast will be used for byte to char conversion. - */ - public SessionInputBufferImpl( - final HttpTransportMetricsImpl metrics, - final int buffersize, - final int minChunkLimit, - final MessageConstraints constraints, - final CharsetDecoder chardecoder) { - Args.notNull(metrics, "HTTP transport metrcis"); - Args.positive(buffersize, "Buffer size"); - this.metrics = metrics; - this.buffer = new byte[buffersize]; - this.bufferpos = 0; - this.bufferlen = 0; - this.minChunkLimit = minChunkLimit >= 0 ? minChunkLimit : 512; - this.constraints = constraints != null ? constraints : MessageConstraints.DEFAULT; - this.linebuffer = new ByteArrayBuffer(buffersize); - this.decoder = chardecoder; - } - - public SessionInputBufferImpl( - final HttpTransportMetricsImpl metrics, - final int buffersize) { - this(metrics, buffersize, buffersize, null, null); - } - - public void bind(final InputStream instream) { - this.instream = instream; - } - - public boolean isBound() { - return this.instream != null; - } - - public int capacity() { - return this.buffer.length; - } - - public int length() { - return this.bufferlen - this.bufferpos; - } - - public int available() { - return capacity() - length(); - } - - private int streamRead(final byte[] b, final int off, final int len) throws IOException { - Asserts.notNull(this.instream, "Input stream"); - return this.instream.read(b, off, len); - } - - public int fillBuffer() throws IOException { - // compact the buffer if necessary - if (this.bufferpos > 0) { - final int len = this.bufferlen - this.bufferpos; - if (len > 0) { - System.arraycopy(this.buffer, this.bufferpos, this.buffer, 0, len); - } - this.bufferpos = 0; - this.bufferlen = len; - } - final int l; - final int off = this.bufferlen; - final int len = this.buffer.length - off; - l = streamRead(this.buffer, off, len); - if (l == -1) { - return -1; - } else { - this.bufferlen = off + l; - this.metrics.incrementBytesTransferred(l); - return l; - } - } - - public boolean hasBufferedData() { - return this.bufferpos < this.bufferlen; - } - - public void clear() { - this.bufferpos = 0; - this.bufferlen = 0; - } - - public int read() throws IOException { - int noRead; - while (!hasBufferedData()) { - noRead = fillBuffer(); - if (noRead == -1) { - return -1; - } - } - return this.buffer[this.bufferpos++] & 0xff; - } - - public int read(final byte[] b, final int off, final int len) throws IOException { - if (b == null) { - return 0; - } - if (hasBufferedData()) { - final int chunk = Math.min(len, this.bufferlen - this.bufferpos); - System.arraycopy(this.buffer, this.bufferpos, b, off, chunk); - this.bufferpos += chunk; - return chunk; - } - // If the remaining capacity is big enough, read directly from the - // underlying input stream bypassing the buffer. - if (len > this.minChunkLimit) { - final int read = streamRead(b, off, len); - if (read > 0) { - this.metrics.incrementBytesTransferred(read); - } - return read; - } else { - // otherwise read to the buffer first - while (!hasBufferedData()) { - final int noRead = fillBuffer(); - if (noRead == -1) { - return -1; - } - } - final int chunk = Math.min(len, this.bufferlen - this.bufferpos); - System.arraycopy(this.buffer, this.bufferpos, b, off, chunk); - this.bufferpos += chunk; - return chunk; - } - } - - public int read(final byte[] b) throws IOException { - if (b == null) { - return 0; - } - return read(b, 0, b.length); - } - - private int locateLF() { - for (int i = this.bufferpos; i < this.bufferlen; i++) { - if (this.buffer[i] == HTTP.LF) { - return i; - } - } - return -1; - } - - /** - * Reads a complete line of characters up to a line delimiter from this - * session buffer into the given line buffer. The number of chars actually - * read is returned as an integer. The line delimiter itself is discarded. - * If no char is available because the end of the stream has been reached, - * the value -1 is returned. This method blocks until input - * data is available, end of file is detected, or an exception is thrown. - *

    - * This method treats a lone LF as a valid line delimiters in addition - * to CR-LF required by the HTTP specification. - * - * @param charbuffer the line buffer. - * @return one line of characters - * @exception IOException if an I/O error occurs. - */ - public int readLine(final CharArrayBuffer charbuffer) throws IOException { - Args.notNull(charbuffer, "Char array buffer"); - int noRead = 0; - boolean retry = true; - while (retry) { - // attempt to find end of line (LF) - final int i = locateLF(); - if (i != -1) { - // end of line found. - if (this.linebuffer.isEmpty()) { - // the entire line is preset in the read buffer - return lineFromReadBuffer(charbuffer, i); - } - retry = false; - final int len = i + 1 - this.bufferpos; - this.linebuffer.append(this.buffer, this.bufferpos, len); - this.bufferpos = i + 1; - } else { - // end of line not found - if (hasBufferedData()) { - final int len = this.bufferlen - this.bufferpos; - this.linebuffer.append(this.buffer, this.bufferpos, len); - this.bufferpos = this.bufferlen; - } - noRead = fillBuffer(); - if (noRead == -1) { - retry = false; - } - } - final int maxLineLen = this.constraints.getMaxLineLength(); - if (maxLineLen > 0 && this.linebuffer.length() >= maxLineLen) { - throw new MessageConstraintException("Maximum line length limit exceeded"); - } - } - if (noRead == -1 && this.linebuffer.isEmpty()) { - // indicate the end of stream - return -1; - } - return lineFromLineBuffer(charbuffer); - } - - /** - * Reads a complete line of characters up to a line delimiter from this - * session buffer. The line delimiter itself is discarded. If no char is - * available because the end of the stream has been reached, - * null is returned. This method blocks until input data is - * available, end of file is detected, or an exception is thrown. - *

    - * This method treats a lone LF as a valid line delimiters in addition - * to CR-LF required by the HTTP specification. - * - * @return HTTP line as a string - * @exception IOException if an I/O error occurs. - */ - private int lineFromLineBuffer(final CharArrayBuffer charbuffer) - throws IOException { - // discard LF if found - int len = this.linebuffer.length(); - if (len > 0) { - if (this.linebuffer.byteAt(len - 1) == HTTP.LF) { - len--; - } - // discard CR if found - if (len > 0) { - if (this.linebuffer.byteAt(len - 1) == HTTP.CR) { - len--; - } - } - } - if (this.decoder == null) { - charbuffer.append(this.linebuffer, 0, len); - } else { - final ByteBuffer bbuf = ByteBuffer.wrap(this.linebuffer.buffer(), 0, len); - len = appendDecoded(charbuffer, bbuf); - } - this.linebuffer.clear(); - return len; - } - - private int lineFromReadBuffer(final CharArrayBuffer charbuffer, final int position) - throws IOException { - int pos = position; - final int off = this.bufferpos; - int len; - this.bufferpos = pos + 1; - if (pos > off && this.buffer[pos - 1] == HTTP.CR) { - // skip CR if found - pos--; - } - len = pos - off; - if (this.decoder == null) { - charbuffer.append(this.buffer, off, len); - } else { - final ByteBuffer bbuf = ByteBuffer.wrap(this.buffer, off, len); - len = appendDecoded(charbuffer, bbuf); - } - return len; - } - - private int appendDecoded( - final CharArrayBuffer charbuffer, final ByteBuffer bbuf) throws IOException { - if (!bbuf.hasRemaining()) { - return 0; - } - if (this.cbuf == null) { - this.cbuf = CharBuffer.allocate(1024); - } - this.decoder.reset(); - int len = 0; - while (bbuf.hasRemaining()) { - final CoderResult result = this.decoder.decode(bbuf, this.cbuf, true); - len += handleDecodingResult(result, charbuffer, bbuf); - } - final CoderResult result = this.decoder.flush(this.cbuf); - len += handleDecodingResult(result, charbuffer, bbuf); - this.cbuf.clear(); - return len; - } - - private int handleDecodingResult( - final CoderResult result, - final CharArrayBuffer charbuffer, - final ByteBuffer bbuf) throws IOException { - if (result.isError()) { - result.throwException(); - } - this.cbuf.flip(); - final int len = this.cbuf.remaining(); - while (this.cbuf.hasRemaining()) { - charbuffer.append(this.cbuf.get()); - } - this.cbuf.compact(); - return len; - } - - public String readLine() throws IOException { - final CharArrayBuffer charbuffer = new CharArrayBuffer(64); - final int l = readLine(charbuffer); - if (l != -1) { - return charbuffer.toString(); - } else { - return null; - } - } - - public boolean isDataAvailable(final int timeout) throws IOException { - return hasBufferedData(); - } - - public HttpTransportMetrics getMetrics() { - return this.metrics; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/SessionOutputBufferImpl.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/SessionOutputBufferImpl.java deleted file mode 100644 index 708b4927..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/SessionOutputBufferImpl.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import java.io.IOException; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CoderResult; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.io.BufferInfo; -import org.apache.http.io.HttpTransportMetrics; -import org.apache.http.io.SessionOutputBuffer; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.Args; -import org.apache.http.util.Asserts; -import org.apache.http.util.ByteArrayBuffer; -import org.apache.http.util.CharArrayBuffer; - -/** - * Abstract base class for session output buffers that stream data to - * an arbitrary {@link OutputStream}. This class buffers small chunks of - * output data in an internal byte array for optimal output performance. - *

    - * {@link #writeLine(CharArrayBuffer)} and {@link #writeLine(String)} methods - * of this class use CR-LF as a line delimiter. - * - * @since 4.3 - */ -@NotThreadSafe -public class SessionOutputBufferImpl implements SessionOutputBuffer, BufferInfo { - - private static final byte[] CRLF = new byte[] {HTTP.CR, HTTP.LF}; - - private final HttpTransportMetricsImpl metrics; - private final ByteArrayBuffer buffer; - private final int fragementSizeHint; - private final CharsetEncoder encoder; - - private OutputStream outstream; - private ByteBuffer bbuf; - - /** - * Creates new instance of SessionOutputBufferImpl. - * - * @param metrics HTTP transport metrics. - * @param buffersize buffer size. Must be a positive number. - * @param fragementSizeHint fragment size hint defining a minimal size of a fragment - * that should be written out directly to the socket bypassing the session buffer. - * Value 0 disables fragment buffering. - * @param charencoder charencoder to be used for encoding HTTP protocol elements. - * If null simple type cast will be used for char to byte conversion. - */ - public SessionOutputBufferImpl( - final HttpTransportMetricsImpl metrics, - final int buffersize, - final int fragementSizeHint, - final CharsetEncoder charencoder) { - super(); - Args.positive(buffersize, "Buffer size"); - Args.notNull(metrics, "HTTP transport metrcis"); - this.metrics = metrics; - this.buffer = new ByteArrayBuffer(buffersize); - this.fragementSizeHint = fragementSizeHint >= 0 ? fragementSizeHint : 0; - this.encoder = charencoder; - } - - public SessionOutputBufferImpl( - final HttpTransportMetricsImpl metrics, - final int buffersize) { - this(metrics, buffersize, buffersize, null); - } - - public void bind(final OutputStream outstream) { - this.outstream = outstream; - } - - public boolean isBound() { - return this.outstream != null; - } - - public int capacity() { - return this.buffer.capacity(); - } - - public int length() { - return this.buffer.length(); - } - - public int available() { - return capacity() - length(); - } - - private void streamWrite(final byte[] b, final int off, final int len) throws IOException { - Asserts.notNull(outstream, "Output stream"); - this.outstream.write(b, off, len); - } - - private void flushStream() throws IOException { - if (this.outstream != null) { - this.outstream.flush(); - } - } - - private void flushBuffer() throws IOException { - final int len = this.buffer.length(); - if (len > 0) { - streamWrite(this.buffer.buffer(), 0, len); - this.buffer.clear(); - this.metrics.incrementBytesTransferred(len); - } - } - - public void flush() throws IOException { - flushBuffer(); - flushStream(); - } - - public void write(final byte[] b, final int off, final int len) throws IOException { - if (b == null) { - return; - } - // Do not want to buffer large-ish chunks - // if the byte array is larger then MIN_CHUNK_LIMIT - // write it directly to the output stream - if (len > this.fragementSizeHint || len > this.buffer.capacity()) { - // flush the buffer - flushBuffer(); - // write directly to the out stream - streamWrite(b, off, len); - this.metrics.incrementBytesTransferred(len); - } else { - // Do not let the buffer grow unnecessarily - final int freecapacity = this.buffer.capacity() - this.buffer.length(); - if (len > freecapacity) { - // flush the buffer - flushBuffer(); - } - // buffer - this.buffer.append(b, off, len); - } - } - - public void write(final byte[] b) throws IOException { - if (b == null) { - return; - } - write(b, 0, b.length); - } - - public void write(final int b) throws IOException { - if (this.fragementSizeHint > 0) { - if (this.buffer.isFull()) { - flushBuffer(); - } - this.buffer.append(b); - } else { - flushBuffer(); - this.outstream.write(b); - } - } - - /** - * Writes characters from the specified string followed by a line delimiter - * to this session buffer. - *

    - * This method uses CR-LF as a line delimiter. - * - * @param s the line. - * @exception IOException if an I/O error occurs. - */ - public void writeLine(final String s) throws IOException { - if (s == null) { - return; - } - if (s.length() > 0) { - if (this.encoder == null) { - for (int i = 0; i < s.length(); i++) { - write(s.charAt(i)); - } - } else { - final CharBuffer cbuf = CharBuffer.wrap(s); - writeEncoded(cbuf); - } - } - write(CRLF); - } - - /** - * Writes characters from the specified char array followed by a line - * delimiter to this session buffer. - *

    - * This method uses CR-LF as a line delimiter. - * - * @param charbuffer the buffer containing chars of the line. - * @exception IOException if an I/O error occurs. - */ - public void writeLine(final CharArrayBuffer charbuffer) throws IOException { - if (charbuffer == null) { - return; - } - if (this.encoder == null) { - int off = 0; - int remaining = charbuffer.length(); - while (remaining > 0) { - int chunk = this.buffer.capacity() - this.buffer.length(); - chunk = Math.min(chunk, remaining); - if (chunk > 0) { - this.buffer.append(charbuffer, off, chunk); - } - if (this.buffer.isFull()) { - flushBuffer(); - } - off += chunk; - remaining -= chunk; - } - } else { - final CharBuffer cbuf = CharBuffer.wrap(charbuffer.buffer(), 0, charbuffer.length()); - writeEncoded(cbuf); - } - write(CRLF); - } - - private void writeEncoded(final CharBuffer cbuf) throws IOException { - if (!cbuf.hasRemaining()) { - return; - } - if (this.bbuf == null) { - this.bbuf = ByteBuffer.allocate(1024); - } - this.encoder.reset(); - while (cbuf.hasRemaining()) { - final CoderResult result = this.encoder.encode(cbuf, this.bbuf, true); - handleEncodingResult(result); - } - final CoderResult result = this.encoder.flush(this.bbuf); - handleEncodingResult(result); - this.bbuf.clear(); - } - - private void handleEncodingResult(final CoderResult result) throws IOException { - if (result.isError()) { - result.throwException(); - } - this.bbuf.flip(); - while (this.bbuf.hasRemaining()) { - write(this.bbuf.get()); - } - this.bbuf.compact(); - } - - public HttpTransportMetrics getMetrics() { - return this.metrics; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/io/package-info.java deleted file mode 100644 index 92c94865..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/io/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Default implementations of message parses and writers - * for synchronous, blocking communication. - */ -package org.apache.http.impl.io; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/package-info.java deleted file mode 100644 index a372c96a..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Default implementations of HTTP connections for synchronous, - * blocking communication. - */ -package org.apache.http.impl; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/pool/BasicConnFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/pool/BasicConnFactory.java deleted file mode 100644 index 07fb7671..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/pool/BasicConnFactory.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.pool; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; - -import javax.net.SocketFactory; -import javax.net.ssl.SSLSocketFactory; - -import org.apache.http.HttpClientConnection; -import org.apache.http.HttpConnectionFactory; -import org.apache.http.HttpHost; -import org.apache.http.annotation.Immutable; -import org.apache.http.config.ConnectionConfig; -import org.apache.http.config.SocketConfig; -import org.apache.http.impl.DefaultBHttpClientConnection; -import org.apache.http.impl.DefaultBHttpClientConnectionFactory; -import org.apache.http.params.CoreConnectionPNames; -import org.apache.http.params.HttpParamConfig; -import org.apache.http.params.HttpParams; -import org.apache.http.pool.ConnFactory; -import org.apache.http.util.Args; - -/** - * A very basic {@link ConnFactory} implementation that creates - * {@link HttpClientConnection} instances given a {@link HttpHost} instance. - * - * @see HttpHost - * @since 4.2 - */ -@SuppressWarnings("deprecation") -@Immutable -public class BasicConnFactory implements ConnFactory { - - private final SocketFactory plainfactory; - private final SSLSocketFactory sslfactory; - private final int connectTimeout; - private final SocketConfig sconfig; - private final HttpConnectionFactory connFactory; - - /** - * @deprecated (4.3) use - * {@link BasicConnFactory#BasicConnFactory(SocketFactory, SSLSocketFactory, int, - * SocketConfig, ConnectionConfig)}. - */ - @Deprecated - public BasicConnFactory(final SSLSocketFactory sslfactory, final HttpParams params) { - super(); - Args.notNull(params, "HTTP params"); - this.plainfactory = null; - this.sslfactory = sslfactory; - this.connectTimeout = params.getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 0); - this.sconfig = HttpParamConfig.getSocketConfig(params); - this.connFactory = new DefaultBHttpClientConnectionFactory( - HttpParamConfig.getConnectionConfig(params)); - } - - /** - * @deprecated (4.3) use - * {@link BasicConnFactory#BasicConnFactory(int, SocketConfig, ConnectionConfig)}. - */ - @Deprecated - public BasicConnFactory(final HttpParams params) { - this(null, params); - } - - /** - * @since 4.3 - */ - public BasicConnFactory( - final SocketFactory plainfactory, - final SSLSocketFactory sslfactory, - final int connectTimeout, - final SocketConfig sconfig, - final ConnectionConfig cconfig) { - super(); - this.plainfactory = plainfactory; - this.sslfactory = sslfactory; - this.connectTimeout = connectTimeout; - this.sconfig = sconfig != null ? sconfig : SocketConfig.DEFAULT; - this.connFactory = new DefaultBHttpClientConnectionFactory( - cconfig != null ? cconfig : ConnectionConfig.DEFAULT); - } - - /** - * @since 4.3 - */ - public BasicConnFactory( - final int connectTimeout, final SocketConfig sconfig, final ConnectionConfig cconfig) { - this(null, null, connectTimeout, sconfig, cconfig); - } - - /** - * @since 4.3 - */ - public BasicConnFactory(final SocketConfig sconfig, final ConnectionConfig cconfig) { - this(null, null, 0, sconfig, cconfig); - } - - /** - * @since 4.3 - */ - public BasicConnFactory() { - this(null, null, 0, SocketConfig.DEFAULT, ConnectionConfig.DEFAULT); - } - - /** - * @deprecated (4.3) no longer used. - */ - @Deprecated - protected HttpClientConnection create(final Socket socket, final HttpParams params) throws IOException { - final int bufsize = params.getIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024); - final DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(bufsize); - conn.bind(socket); - return conn; - } - - public HttpClientConnection create(final HttpHost host) throws IOException { - final String scheme = host.getSchemeName(); - Socket socket = null; - if ("http".equalsIgnoreCase(scheme)) { - socket = this.plainfactory != null ? this.plainfactory.createSocket() : - new Socket(); - } if ("https".equalsIgnoreCase(scheme)) { - socket = (this.sslfactory != null ? this.sslfactory : - SSLSocketFactory.getDefault()).createSocket(); - } - if (socket == null) { - throw new IOException(scheme + " scheme is not supported"); - } - final String hostname = host.getHostName(); - int port = host.getPort(); - if (port == -1) { - if (host.getSchemeName().equalsIgnoreCase("http")) { - port = 80; - } else if (host.getSchemeName().equalsIgnoreCase("https")) { - port = 443; - } - } - socket.setSoTimeout(this.sconfig.getSoTimeout()); - socket.connect(new InetSocketAddress(hostname, port), this.connectTimeout); - socket.setTcpNoDelay(this.sconfig.isTcpNoDelay()); - final int linger = this.sconfig.getSoLinger(); - if (linger >= 0) { - socket.setSoLinger(linger > 0, linger); - } - socket.setKeepAlive(this.sconfig.isSoKeepAlive()); - return this.connFactory.createConnection(socket); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/pool/BasicConnPool.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/pool/BasicConnPool.java deleted file mode 100644 index fa1f4ebe..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/pool/BasicConnPool.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.pool; - -import java.util.concurrent.atomic.AtomicLong; - -import org.apache.http.HttpClientConnection; -import org.apache.http.HttpHost; -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.config.ConnectionConfig; -import org.apache.http.config.SocketConfig; -import org.apache.http.params.HttpParams; -import org.apache.http.pool.AbstractConnPool; -import org.apache.http.pool.ConnFactory; - -/** - * A very basic {@link org.apache.http.pool.ConnPool} implementation that - * represents a pool of blocking {@link HttpClientConnection} connections - * identified by an {@link HttpHost} instance. Please note this pool - * implementation does not support complex routes via a proxy cannot - * differentiate between direct and proxied connections. - * - * @see HttpHost - * @since 4.2 - */ -@SuppressWarnings("deprecation") -@ThreadSafe -public class BasicConnPool extends AbstractConnPool { - - private static final AtomicLong COUNTER = new AtomicLong(); - - public BasicConnPool(final ConnFactory connFactory) { - super(connFactory, 2, 20); - } - - /** - * @deprecated (4.3) use {@link BasicConnPool#BasicConnPool(SocketConfig, ConnectionConfig)} - */ - @Deprecated - public BasicConnPool(final HttpParams params) { - super(new BasicConnFactory(params), 2, 20); - } - - /** - * @since 4.3 - */ - public BasicConnPool(final SocketConfig sconfig, final ConnectionConfig cconfig) { - super(new BasicConnFactory(sconfig, cconfig), 2, 20); - } - - /** - * @since 4.3 - */ - public BasicConnPool() { - super(new BasicConnFactory(SocketConfig.DEFAULT, ConnectionConfig.DEFAULT), 2, 20); - } - - @Override - protected BasicPoolEntry createEntry( - final HttpHost host, - final HttpClientConnection conn) { - return new BasicPoolEntry(Long.toString(COUNTER.getAndIncrement()), host, conn); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/pool/BasicPoolEntry.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/pool/BasicPoolEntry.java deleted file mode 100644 index 521d1d34..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/pool/BasicPoolEntry.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.pool; - -import java.io.IOException; - -import org.apache.http.HttpClientConnection; -import org.apache.http.HttpHost; -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.pool.PoolEntry; - -/** - * A very basic {@link PoolEntry} implementation that represents an entry - * in a pool of blocking {@link HttpClientConnection}s identified by - * an {@link HttpHost} instance. - * - * @see HttpHost - * @since 4.2 - */ -@ThreadSafe -public class BasicPoolEntry extends PoolEntry { - - public BasicPoolEntry(final String id, final HttpHost route, final HttpClientConnection conn) { - super(id, route, conn); - } - - @Override - public void close() { - try { - this.getConnection().close(); - } catch (final IOException ignore) { - } - } - - @Override - public boolean isClosed() { - return !this.getConnection().isOpen(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/impl/pool/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/impl/pool/package-info.java deleted file mode 100644 index 56d7e7f3..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/impl/pool/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Default implementations of client side connection pools - * for synchronous, blocking communication. - */ -package org.apache.http.impl.pool; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/io/BufferInfo.java b/lib/httpclient-android/src/main/java/org/apache/http/io/BufferInfo.java deleted file mode 100644 index 75a81412..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/io/BufferInfo.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.io; - -/** - * Basic buffer properties. - * - * @since 4.1 - */ -public interface BufferInfo { - - /** - * Return length data stored in the buffer - * - * @return data length - */ - int length(); - - /** - * Returns total capacity of the buffer - * - * @return total capacity - */ - int capacity(); - - /** - * Returns available space in the buffer. - * - * @return available space. - */ - int available(); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/io/HttpMessageParserFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/io/HttpMessageParserFactory.java deleted file mode 100644 index 010c6b44..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/io/HttpMessageParserFactory.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.io; - -import org.apache.http.HttpMessage; -import org.apache.http.config.MessageConstraints; - -/** - * Factory for {@link HttpMessageParser} instances. - * - * @since 4.3 - */ -public interface HttpMessageParserFactory { - - HttpMessageParser create(SessionInputBuffer buffer, MessageConstraints constraints); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/io/HttpMessageWriterFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/io/HttpMessageWriterFactory.java deleted file mode 100644 index 7b01409f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/io/HttpMessageWriterFactory.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.io; - -import org.apache.http.HttpMessage; - -/** - * Factory for {@link HttpMessageWriter} instances. - * - * @since 4.3 - */ -public interface HttpMessageWriterFactory { - - HttpMessageWriter create(SessionOutputBuffer buffer); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/io/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/io/package-info.java deleted file mode 100644 index e9703103..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/io/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * HTTP message parser and writer APIs for synchronous, blocking - * communication. - */ -package org.apache.http.io; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/message/BasicHeaderValueFormatterHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/message/BasicHeaderValueFormatterHC4.java deleted file mode 100644 index 2350c2b5..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/message/BasicHeaderValueFormatterHC4.java +++ /dev/null @@ -1,422 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.message; - -import org.apache.http.HeaderElement; -import org.apache.http.NameValuePair; -import org.apache.http.annotation.Immutable; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * Basic implementation for formatting header value elements. - * Instances of this class are stateless and thread-safe. - * Derived classes are expected to maintain these properties. - * - * @since 4.0 - */ -@Immutable -public class BasicHeaderValueFormatterHC4 implements HeaderValueFormatter { - - /** - * A default instance of this class, for use as default or fallback. - * Note that {@link BasicHeaderValueFormatter} is not a singleton, there - * can be many instances of the class itself and of derived classes. - * The instance here provides non-customized, default behavior. - * - * @deprecated (4.3) use {@link #INSTANCE} - */ - @Deprecated - public final static - BasicHeaderValueFormatterHC4 DEFAULT = new BasicHeaderValueFormatterHC4(); - - public final static BasicHeaderValueFormatterHC4 INSTANCE = new BasicHeaderValueFormatterHC4(); - - /** - * Special characters that can be used as separators in HTTP parameters. - * These special characters MUST be in a quoted string to be used within - * a parameter value . - */ - public final static String SEPARATORS = " ;,:@()<>\\\"/[]?={}\t"; - - /** - * Unsafe special characters that must be escaped using the backslash - * character - */ - public final static String UNSAFE_CHARS = "\"\\"; - - public BasicHeaderValueFormatterHC4() { - super(); - } - - /** - * Formats an array of header elements. - * - * @param elems the header elements to format - * @param quote true to always format with quoted values, - * false to use quotes only when necessary - * @param formatter the formatter to use, or null - * for the {@link #INSTANCE default} - * - * @return the formatted header elements - */ - public static - String formatElements(final HeaderElement[] elems, - final boolean quote, - final HeaderValueFormatter formatter) { - return (formatter != null ? formatter : BasicHeaderValueFormatterHC4.INSTANCE) - .formatElements(null, elems, quote).toString(); - } - - - // non-javadoc, see interface HeaderValueFormatter - public CharArrayBuffer formatElements(final CharArrayBuffer charBuffer, - final HeaderElement[] elems, - final boolean quote) { - Args.notNull(elems, "Header element array"); - final int len = estimateElementsLen(elems); - CharArrayBuffer buffer = charBuffer; - if (buffer == null) { - buffer = new CharArrayBuffer(len); - } else { - buffer.ensureCapacity(len); - } - - for (int i=0; i 0) { - buffer.append(", "); - } - formatHeaderElement(buffer, elems[i], quote); - } - - return buffer; - } - - - /** - * Estimates the length of formatted header elements. - * - * @param elems the header elements to format, or null - * - * @return a length estimate, in number of characters - */ - protected int estimateElementsLen(final HeaderElement[] elems) { - if ((elems == null) || (elems.length < 1)) { - return 0; - } - - int result = (elems.length-1) * 2; // elements separated by ", " - for (final HeaderElement elem : elems) { - result += estimateHeaderElementLen(elem); - } - - return result; - } - - - - /** - * Formats a header element. - * - * @param elem the header element to format - * @param quote true to always format with quoted values, - * false to use quotes only when necessary - * @param formatter the formatter to use, or null - * for the {@link #INSTANCE default} - * - * @return the formatted header element - */ - public static - String formatHeaderElement(final HeaderElement elem, - final boolean quote, - final HeaderValueFormatter formatter) { - return (formatter != null ? formatter : BasicHeaderValueFormatterHC4.INSTANCE) - .formatHeaderElement(null, elem, quote).toString(); - } - - - // non-javadoc, see interface HeaderValueFormatter - public CharArrayBuffer formatHeaderElement(final CharArrayBuffer charBuffer, - final HeaderElement elem, - final boolean quote) { - Args.notNull(elem, "Header element"); - final int len = estimateHeaderElementLen(elem); - CharArrayBuffer buffer = charBuffer; - if (buffer == null) { - buffer = new CharArrayBuffer(len); - } else { - buffer.ensureCapacity(len); - } - - buffer.append(elem.getName()); - final String value = elem.getValue(); - if (value != null) { - buffer.append('='); - doFormatValue(buffer, value, quote); - } - - final int parcnt = elem.getParameterCount(); - if (parcnt > 0) { - for (int i=0; inull - * - * @return a length estimate, in number of characters - */ - protected int estimateHeaderElementLen(final HeaderElement elem) { - if (elem == null) { - return 0; - } - - int result = elem.getName().length(); // name - final String value = elem.getValue(); - if (value != null) { - // assume quotes, but no escaped characters - result += 3 + value.length(); // ="value" - } - - final int parcnt = elem.getParameterCount(); - if (parcnt > 0) { - for (int i=0; i - estimateNameValuePairLen(elem.getParameter(i)); - } - } - - return result; - } - - - - - /** - * Formats a set of parameters. - * - * @param nvps the parameters to format - * @param quote true to always format with quoted values, - * false to use quotes only when necessary - * @param formatter the formatter to use, or null - * for the {@link #INSTANCE default} - * - * @return the formatted parameters - */ - public static - String formatParameters(final NameValuePair[] nvps, - final boolean quote, - final HeaderValueFormatter formatter) { - return (formatter != null ? formatter : BasicHeaderValueFormatterHC4.INSTANCE) - .formatParameters(null, nvps, quote).toString(); - } - - - // non-javadoc, see interface HeaderValueFormatter - public CharArrayBuffer formatParameters(final CharArrayBuffer charBuffer, - final NameValuePair[] nvps, - final boolean quote) { - Args.notNull(nvps, "Header parameter array"); - final int len = estimateParametersLen(nvps); - CharArrayBuffer buffer = charBuffer; - if (buffer == null) { - buffer = new CharArrayBuffer(len); - } else { - buffer.ensureCapacity(len); - } - - for (int i = 0; i < nvps.length; i++) { - if (i > 0) { - buffer.append("; "); - } - formatNameValuePair(buffer, nvps[i], quote); - } - - return buffer; - } - - - /** - * Estimates the length of formatted parameters. - * - * @param nvps the parameters to format, or null - * - * @return a length estimate, in number of characters - */ - protected int estimateParametersLen(final NameValuePair[] nvps) { - if ((nvps == null) || (nvps.length < 1)) { - return 0; - } - - int result = (nvps.length-1) * 2; // "; " between the parameters - for (final NameValuePair nvp : nvps) { - result += estimateNameValuePairLen(nvp); - } - - return result; - } - - - /** - * Formats a name-value pair. - * - * @param nvp the name-value pair to format - * @param quote true to always format with a quoted value, - * false to use quotes only when necessary - * @param formatter the formatter to use, or null - * for the {@link #INSTANCE default} - * - * @return the formatted name-value pair - */ - public static - String formatNameValuePair(final NameValuePair nvp, - final boolean quote, - final HeaderValueFormatter formatter) { - return (formatter != null ? formatter : BasicHeaderValueFormatterHC4.INSTANCE) - .formatNameValuePair(null, nvp, quote).toString(); - } - - - // non-javadoc, see interface HeaderValueFormatter - public CharArrayBuffer formatNameValuePair(final CharArrayBuffer charBuffer, - final NameValuePair nvp, - final boolean quote) { - Args.notNull(nvp, "Name / value pair"); - final int len = estimateNameValuePairLen(nvp); - CharArrayBuffer buffer = charBuffer; - if (buffer == null) { - buffer = new CharArrayBuffer(len); - } else { - buffer.ensureCapacity(len); - } - - buffer.append(nvp.getName()); - final String value = nvp.getValue(); - if (value != null) { - buffer.append('='); - doFormatValue(buffer, value, quote); - } - - return buffer; - } - - - /** - * Estimates the length of a formatted name-value pair. - * - * @param nvp the name-value pair to format, or null - * - * @return a length estimate, in number of characters - */ - protected int estimateNameValuePairLen(final NameValuePair nvp) { - if (nvp == null) { - return 0; - } - - int result = nvp.getName().length(); // name - final String value = nvp.getValue(); - if (value != null) { - // assume quotes, but no escaped characters - result += 3 + value.length(); // ="value" - } - return result; - } - - - /** - * Actually formats the value of a name-value pair. - * This does not include a leading = character. - * Called from {@link #formatNameValuePair formatNameValuePair}. - * - * @param buffer the buffer to append to, never null - * @param value the value to append, never null - * @param quote true to always format with quotes, - * false to use quotes only when necessary - */ - protected void doFormatValue(final CharArrayBuffer buffer, - final String value, - final boolean quote) { - - boolean quoteFlag = quote; - if (!quoteFlag) { - for (int i = 0; (i < value.length()) && !quoteFlag; i++) { - quoteFlag = isSeparator(value.charAt(i)); - } - } - - if (quoteFlag) { - buffer.append('"'); - } - for (int i = 0; i < value.length(); i++) { - final char ch = value.charAt(i); - if (isUnsafe(ch)) { - buffer.append('\\'); - } - buffer.append(ch); - } - if (quoteFlag) { - buffer.append('"'); - } - } - - - /** - * Checks whether a character is a {@link #SEPARATORS separator}. - * - * @param ch the character to check - * - * @return true if the character is a separator, - * false otherwise - */ - protected boolean isSeparator(final char ch) { - return SEPARATORS.indexOf(ch) >= 0; - } - - - /** - * Checks whether a character is {@link #UNSAFE_CHARS unsafe}. - * - * @param ch the character to check - * - * @return true if the character is unsafe, - * false otherwise - */ - protected boolean isUnsafe(final char ch) { - return UNSAFE_CHARS.indexOf(ch) >= 0; - } - - -} // class BasicHeaderValueFormatterHC4 diff --git a/lib/httpclient-android/src/main/java/org/apache/http/message/BasicHeaderValueParserHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/message/BasicHeaderValueParserHC4.java deleted file mode 100644 index c6efdc35..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/message/BasicHeaderValueParserHC4.java +++ /dev/null @@ -1,359 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.message; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.http.HeaderElement; -import org.apache.http.NameValuePair; -import org.apache.http.ParseException; -import org.apache.http.annotation.Immutable; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * Basic implementation for parsing header values into elements. - * Instances of this class are stateless and thread-safe. - * Derived classes are expected to maintain these properties. - * - * @since 4.0 - */ -@Immutable -public class BasicHeaderValueParserHC4 implements HeaderValueParser { - - /** - * A default instance of this class, for use as default or fallback. - * Note that {@link BasicHeaderValueParser} is not a singleton, there - * can be many instances of the class itself and of derived classes. - * The instance here provides non-customized, default behavior. - * - * @deprecated (4.3) use {@link #INSTANCE} - */ - @Deprecated - public final static - BasicHeaderValueParserHC4 DEFAULT = new BasicHeaderValueParserHC4(); - - public final static BasicHeaderValueParserHC4 INSTANCE = new BasicHeaderValueParserHC4(); - - private final static char PARAM_DELIMITER = ';'; - private final static char ELEM_DELIMITER = ','; - private final static char[] ALL_DELIMITERS = new char[] { - PARAM_DELIMITER, - ELEM_DELIMITER - }; - - public BasicHeaderValueParserHC4() { - super(); - } - - /** - * Parses elements with the given parser. - * - * @param value the header value to parse - * @param parser the parser to use, or null for default - * - * @return array holding the header elements, never null - */ - public static - HeaderElement[] parseElements(final String value, - final HeaderValueParser parser) throws ParseException { - Args.notNull(value, "Value"); - - final CharArrayBuffer buffer = new CharArrayBuffer(value.length()); - buffer.append(value); - final ParserCursor cursor = new ParserCursor(0, value.length()); - return (parser != null ? parser : BasicHeaderValueParserHC4.INSTANCE) - .parseElements(buffer, cursor); - } - - - // non-javadoc, see interface HeaderValueParser - public HeaderElement[] parseElements(final CharArrayBuffer buffer, - final ParserCursor cursor) { - Args.notNull(buffer, "Char array buffer"); - Args.notNull(cursor, "Parser cursor"); - final List elements = new ArrayList(); - while (!cursor.atEnd()) { - final HeaderElement element = parseHeaderElement(buffer, cursor); - if (!(element.getName().length() == 0 && element.getValue() == null)) { - elements.add(element); - } - } - return elements.toArray(new HeaderElement[elements.size()]); - } - - - /** - * Parses an element with the given parser. - * - * @param value the header element to parse - * @param parser the parser to use, or null for default - * - * @return the parsed header element - */ - public static - HeaderElement parseHeaderElement(final String value, - final HeaderValueParser parser) throws ParseException { - Args.notNull(value, "Value"); - - final CharArrayBuffer buffer = new CharArrayBuffer(value.length()); - buffer.append(value); - final ParserCursor cursor = new ParserCursor(0, value.length()); - return (parser != null ? parser : BasicHeaderValueParserHC4.INSTANCE) - .parseHeaderElement(buffer, cursor); - } - - - // non-javadoc, see interface HeaderValueParser - public HeaderElement parseHeaderElement(final CharArrayBuffer buffer, - final ParserCursor cursor) { - Args.notNull(buffer, "Char array buffer"); - Args.notNull(cursor, "Parser cursor"); - final NameValuePair nvp = parseNameValuePair(buffer, cursor); - NameValuePair[] params = null; - if (!cursor.atEnd()) { - final char ch = buffer.charAt(cursor.getPos() - 1); - if (ch != ELEM_DELIMITER) { - params = parseParameters(buffer, cursor); - } - } - return createHeaderElement(nvp.getName(), nvp.getValue(), params); - } - - - /** - * Creates a header element. - * Called from {@link #parseHeaderElement}. - * - * @return a header element representing the argument - */ - protected HeaderElement createHeaderElement( - final String name, - final String value, - final NameValuePair[] params) { - return new BasicHeaderElement(name, value, params); - } - - - /** - * Parses parameters with the given parser. - * - * @param value the parameter list to parse - * @param parser the parser to use, or null for default - * - * @return array holding the parameters, never null - */ - public static - NameValuePair[] parseParameters(final String value, - final HeaderValueParser parser) throws ParseException { - Args.notNull(value, "Value"); - - final CharArrayBuffer buffer = new CharArrayBuffer(value.length()); - buffer.append(value); - final ParserCursor cursor = new ParserCursor(0, value.length()); - return (parser != null ? parser : BasicHeaderValueParserHC4.INSTANCE) - .parseParameters(buffer, cursor); - } - - - - // non-javadoc, see interface HeaderValueParser - public NameValuePair[] parseParameters(final CharArrayBuffer buffer, - final ParserCursor cursor) { - Args.notNull(buffer, "Char array buffer"); - Args.notNull(cursor, "Parser cursor"); - int pos = cursor.getPos(); - final int indexTo = cursor.getUpperBound(); - - while (pos < indexTo) { - final char ch = buffer.charAt(pos); - if (HTTP.isWhitespace(ch)) { - pos++; - } else { - break; - } - } - cursor.updatePos(pos); - if (cursor.atEnd()) { - return new NameValuePair[] {}; - } - - final List params = new ArrayList(); - while (!cursor.atEnd()) { - final NameValuePair param = parseNameValuePair(buffer, cursor); - params.add(param); - final char ch = buffer.charAt(cursor.getPos() - 1); - if (ch == ELEM_DELIMITER) { - break; - } - } - - return params.toArray(new NameValuePair[params.size()]); - } - - /** - * Parses a name-value-pair with the given parser. - * - * @param value the NVP to parse - * @param parser the parser to use, or null for default - * - * @return the parsed name-value pair - */ - public static - NameValuePair parseNameValuePair(final String value, - final HeaderValueParser parser) throws ParseException { - Args.notNull(value, "Value"); - - final CharArrayBuffer buffer = new CharArrayBuffer(value.length()); - buffer.append(value); - final ParserCursor cursor = new ParserCursor(0, value.length()); - return (parser != null ? parser : BasicHeaderValueParserHC4.INSTANCE) - .parseNameValuePair(buffer, cursor); - } - - - // non-javadoc, see interface HeaderValueParser - public NameValuePair parseNameValuePair(final CharArrayBuffer buffer, - final ParserCursor cursor) { - return parseNameValuePair(buffer, cursor, ALL_DELIMITERS); - } - - private static boolean isOneOf(final char ch, final char[] chs) { - if (chs != null) { - for (final char ch2 : chs) { - if (ch == ch2) { - return true; - } - } - } - return false; - } - - public NameValuePair parseNameValuePair(final CharArrayBuffer buffer, - final ParserCursor cursor, - final char[] delimiters) { - Args.notNull(buffer, "Char array buffer"); - Args.notNull(cursor, "Parser cursor"); - - boolean terminated = false; - - int pos = cursor.getPos(); - final int indexFrom = cursor.getPos(); - final int indexTo = cursor.getUpperBound(); - - // Find name - final String name; - while (pos < indexTo) { - final char ch = buffer.charAt(pos); - if (ch == '=') { - break; - } - if (isOneOf(ch, delimiters)) { - terminated = true; - break; - } - pos++; - } - - if (pos == indexTo) { - terminated = true; - name = buffer.substringTrimmed(indexFrom, indexTo); - } else { - name = buffer.substringTrimmed(indexFrom, pos); - pos++; - } - - if (terminated) { - cursor.updatePos(pos); - return createNameValuePair(name, null); - } - - // Find value - final String value; - int i1 = pos; - - boolean qouted = false; - boolean escaped = false; - while (pos < indexTo) { - final char ch = buffer.charAt(pos); - if (ch == '"' && !escaped) { - qouted = !qouted; - } - if (!qouted && !escaped && isOneOf(ch, delimiters)) { - terminated = true; - break; - } - if (escaped) { - escaped = false; - } else { - escaped = qouted && ch == '\\'; - } - pos++; - } - - int i2 = pos; - // Trim leading white spaces - while (i1 < i2 && (HTTP.isWhitespace(buffer.charAt(i1)))) { - i1++; - } - // Trim trailing white spaces - while ((i2 > i1) && (HTTP.isWhitespace(buffer.charAt(i2 - 1)))) { - i2--; - } - // Strip away quotes if necessary - if (((i2 - i1) >= 2) - && (buffer.charAt(i1) == '"') - && (buffer.charAt(i2 - 1) == '"')) { - i1++; - i2--; - } - value = buffer.substring(i1, i2); - if (terminated) { - pos++; - } - cursor.updatePos(pos); - return createNameValuePair(name, value); - } - - /** - * Creates a name-value pair. - * Called from {@link #parseNameValuePair}. - * - * @param name the name - * @param value the value, or null - * - * @return a name-value pair representing the arguments - */ - protected NameValuePair createNameValuePair(final String name, final String value) { - return new BasicNameValuePair(name, value); - } - -} - diff --git a/lib/httpclient-android/src/main/java/org/apache/http/message/BasicLineFormatterHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/message/BasicLineFormatterHC4.java deleted file mode 100644 index 82a2b53e..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/message/BasicLineFormatterHC4.java +++ /dev/null @@ -1,319 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.message; - -import org.apache.http.FormattedHeader; -import org.apache.http.Header; -import org.apache.http.ProtocolVersion; -import org.apache.http.RequestLine; -import org.apache.http.StatusLine; -import org.apache.http.annotation.Immutable; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * Interface for formatting elements of the HEAD section of an HTTP message. - * This is the complement to {@link LineParser}. - * There are individual methods for formatting a request line, a - * status line, or a header line. The formatting does not include the - * trailing line break sequence CR-LF. - * The formatted lines are returned in memory, the formatter does not depend - * on any specific IO mechanism. - * Instances of this interface are expected to be stateless and thread-safe. - * - * @since 4.0 - */ -@Immutable -public class BasicLineFormatterHC4 implements LineFormatter { - - /** - * A default instance of this class, for use as default or fallback. - * Note that {@link BasicLineFormatter} is not a singleton, there can - * be many instances of the class itself and of derived classes. - * The instance here provides non-customized, default behavior. - * - * @deprecated (4.3) use {@link #INSTANCE} - */ - @Deprecated - public final static BasicLineFormatterHC4 DEFAULT = new BasicLineFormatterHC4(); - - public final static BasicLineFormatterHC4 INSTANCE = new BasicLineFormatterHC4(); - - public BasicLineFormatterHC4() { - super(); - } - - /** - * Obtains a buffer for formatting. - * - * @param charBuffer a buffer already available, or null - * - * @return the cleared argument buffer if there is one, or - * a new empty buffer that can be used for formatting - */ - protected CharArrayBuffer initBuffer(final CharArrayBuffer charBuffer) { - CharArrayBuffer buffer = charBuffer; - if (buffer != null) { - buffer.clear(); - } else { - buffer = new CharArrayBuffer(64); - } - return buffer; - } - - - /** - * Formats a protocol version. - * - * @param version the protocol version to format - * @param formatter the formatter to use, or - * null for the - * {@link #INSTANCE default} - * - * @return the formatted protocol version - */ - public static - String formatProtocolVersion(final ProtocolVersion version, - final LineFormatter formatter) { - return (formatter != null ? formatter : BasicLineFormatterHC4.INSTANCE) - .appendProtocolVersion(null, version).toString(); - } - - - // non-javadoc, see interface LineFormatter - public CharArrayBuffer appendProtocolVersion(final CharArrayBuffer buffer, - final ProtocolVersion version) { - Args.notNull(version, "Protocol version"); - // can't use initBuffer, that would clear the argument! - CharArrayBuffer result = buffer; - final int len = estimateProtocolVersionLen(version); - if (result == null) { - result = new CharArrayBuffer(len); - } else { - result.ensureCapacity(len); - } - - result.append(version.getProtocol()); - result.append('/'); - result.append(Integer.toString(version.getMajor())); - result.append('.'); - result.append(Integer.toString(version.getMinor())); - - return result; - } - - - /** - * Guesses the length of a formatted protocol version. - * Needed to guess the length of a formatted request or status line. - * - * @param version the protocol version to format, or null - * - * @return the estimated length of the formatted protocol version, - * in characters - */ - protected int estimateProtocolVersionLen(final ProtocolVersion version) { - return version.getProtocol().length() + 4; // room for "HTTP/1.1" - } - - - /** - * Formats a request line. - * - * @param reqline the request line to format - * @param formatter the formatter to use, or - * null for the - * {@link #INSTANCE default} - * - * @return the formatted request line - */ - public static String formatRequestLine(final RequestLine reqline, - final LineFormatter formatter) { - return (formatter != null ? formatter : BasicLineFormatterHC4.INSTANCE) - .formatRequestLine(null, reqline).toString(); - } - - - // non-javadoc, see interface LineFormatter - public CharArrayBuffer formatRequestLine(final CharArrayBuffer buffer, - final RequestLine reqline) { - Args.notNull(reqline, "Request line"); - final CharArrayBuffer result = initBuffer(buffer); - doFormatRequestLine(result, reqline); - - return result; - } - - - /** - * Actually formats a request line. - * Called from {@link #formatRequestLine}. - * - * @param buffer the empty buffer into which to format, - * never null - * @param reqline the request line to format, never null - */ - protected void doFormatRequestLine(final CharArrayBuffer buffer, - final RequestLine reqline) { - final String method = reqline.getMethod(); - final String uri = reqline.getUri(); - - // room for "GET /index.html HTTP/1.1" - final int len = method.length() + 1 + uri.length() + 1 + - estimateProtocolVersionLen(reqline.getProtocolVersion()); - buffer.ensureCapacity(len); - - buffer.append(method); - buffer.append(' '); - buffer.append(uri); - buffer.append(' '); - appendProtocolVersion(buffer, reqline.getProtocolVersion()); - } - - - - /** - * Formats a status line. - * - * @param statline the status line to format - * @param formatter the formatter to use, or - * null for the - * {@link #INSTANCE default} - * - * @return the formatted status line - */ - public static String formatStatusLine(final StatusLine statline, - final LineFormatter formatter) { - return (formatter != null ? formatter : BasicLineFormatterHC4.INSTANCE) - .formatStatusLine(null, statline).toString(); - } - - - // non-javadoc, see interface LineFormatter - public CharArrayBuffer formatStatusLine(final CharArrayBuffer buffer, - final StatusLine statline) { - Args.notNull(statline, "Status line"); - final CharArrayBuffer result = initBuffer(buffer); - doFormatStatusLine(result, statline); - - return result; - } - - - /** - * Actually formats a status line. - * Called from {@link #formatStatusLine}. - * - * @param buffer the empty buffer into which to format, - * never null - * @param statline the status line to format, never null - */ - protected void doFormatStatusLine(final CharArrayBuffer buffer, - final StatusLine statline) { - - int len = estimateProtocolVersionLen(statline.getProtocolVersion()) - + 1 + 3 + 1; // room for "HTTP/1.1 200 " - final String reason = statline.getReasonPhrase(); - if (reason != null) { - len += reason.length(); - } - buffer.ensureCapacity(len); - - appendProtocolVersion(buffer, statline.getProtocolVersion()); - buffer.append(' '); - buffer.append(Integer.toString(statline.getStatusCode())); - buffer.append(' '); // keep whitespace even if reason phrase is empty - if (reason != null) { - buffer.append(reason); - } - } - - - /** - * Formats a header. - * - * @param header the header to format - * @param formatter the formatter to use, or - * null for the - * {@link #INSTANCE default} - * - * @return the formatted header - */ - public static String formatHeader(final Header header, - final LineFormatter formatter) { - return (formatter != null ? formatter : BasicLineFormatterHC4.INSTANCE) - .formatHeader(null, header).toString(); - } - - - // non-javadoc, see interface LineFormatter - public CharArrayBuffer formatHeader(final CharArrayBuffer buffer, - final Header header) { - Args.notNull(header, "Header"); - final CharArrayBuffer result; - - if (header instanceof FormattedHeader) { - // If the header is backed by a buffer, re-use the buffer - result = ((FormattedHeader)header).getBuffer(); - } else { - result = initBuffer(buffer); - doFormatHeader(result, header); - } - return result; - - } // formatHeader - - - /** - * Actually formats a header. - * Called from {@link #formatHeader}. - * - * @param buffer the empty buffer into which to format, - * never null - * @param header the header to format, never null - */ - protected void doFormatHeader(final CharArrayBuffer buffer, - final Header header) { - final String name = header.getName(); - final String value = header.getValue(); - - int len = name.length() + 2; - if (value != null) { - len += value.length(); - } - buffer.ensureCapacity(len); - - buffer.append(name); - buffer.append(": "); - if (value != null) { - buffer.append(value); - } - } - - -} // class BasicLineFormatterHC4 diff --git a/lib/httpclient-android/src/main/java/org/apache/http/message/BasicLineParserHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/message/BasicLineParserHC4.java deleted file mode 100644 index e7e19f5d..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/message/BasicLineParserHC4.java +++ /dev/null @@ -1,456 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.message; - -import org.apache.http.Header; -import org.apache.http.HttpVersion; -import org.apache.http.ParseException; -import org.apache.http.ProtocolVersion; -import org.apache.http.RequestLine; -import org.apache.http.StatusLine; -import org.apache.http.annotation.Immutable; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.Args; -import org.apache.http.util.CharArrayBuffer; - -/** - * Basic parser for lines in the head section of an HTTP message. - * There are individual methods for parsing a request line, a - * status line, or a header line. - * The lines to parse are passed in memory, the parser does not depend - * on any specific IO mechanism. - * Instances of this class are stateless and thread-safe. - * Derived classes MUST maintain these properties. - * - *

    - * Note: This class was created by refactoring parsing code located in - * various other classes. The author tags from those other classes have - * been replicated here, although the association with the parsing code - * taken from there has not been traced. - *

    - * - * @since 4.0 - */ -@Immutable -public class BasicLineParserHC4 implements LineParser { - - /** - * A default instance of this class, for use as default or fallback. - * Note that {@link BasicLineParser} is not a singleton, there can - * be many instances of the class itself and of derived classes. - * The instance here provides non-customized, default behavior. - * - * @deprecated (4.3) use {@link #INSTANCE} - */ - @Deprecated - public final static BasicLineParserHC4 DEFAULT = new BasicLineParserHC4(); - - public final static BasicLineParserHC4 INSTANCE = new BasicLineParserHC4(); - - /** - * A version of the protocol to parse. - * The version is typically not relevant, but the protocol name. - */ - protected final ProtocolVersion protocol; - - - /** - * Creates a new line parser for the given HTTP-like protocol. - * - * @param proto a version of the protocol to parse, or - * null for HTTP. The actual version - * is not relevant, only the protocol name. - */ - public BasicLineParserHC4(final ProtocolVersion proto) { - this.protocol = proto != null? proto : HttpVersion.HTTP_1_1; - } - - - /** - * Creates a new line parser for HTTP. - */ - public BasicLineParserHC4() { - this(null); - } - - - public static - ProtocolVersion parseProtocolVersion(final String value, - final LineParser parser) throws ParseException { - Args.notNull(value, "Value"); - - final CharArrayBuffer buffer = new CharArrayBuffer(value.length()); - buffer.append(value); - final ParserCursor cursor = new ParserCursor(0, value.length()); - return (parser != null ? parser : BasicLineParserHC4.INSTANCE) - .parseProtocolVersion(buffer, cursor); - } - - - // non-javadoc, see interface LineParser - public ProtocolVersion parseProtocolVersion(final CharArrayBuffer buffer, - final ParserCursor cursor) throws ParseException { - Args.notNull(buffer, "Char array buffer"); - Args.notNull(cursor, "Parser cursor"); - final String protoname = this.protocol.getProtocol(); - final int protolength = protoname.length(); - - final int indexFrom = cursor.getPos(); - final int indexTo = cursor.getUpperBound(); - - skipWhitespace(buffer, cursor); - - int i = cursor.getPos(); - - // long enough for "HTTP/1.1"? - if (i + protolength + 4 > indexTo) { - throw new ParseException - ("Not a valid protocol version: " + - buffer.substring(indexFrom, indexTo)); - } - - // check the protocol name and slash - boolean ok = true; - for (int j=0; ok && (j buffer.length()) { - return false; - } - - - // just check protocol name and slash, no need to analyse the version - boolean ok = true; - for (int j=0; ok && (j. - * - */ - -/** - * Core HTTP message components, message element parser - * and writer APIs and their default implementations. - */ -package org.apache.http.message; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/package-info.java deleted file mode 100644 index 9d9747ac..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/package-info.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Core HTTP component APIs and primitives. - *

    - * These deal with the fundamental things required for using the - * HTTP protocol, such as representing a - * {@link org.apache.http.HttpMessage message} including it's - * {@link org.apache.http.Header headers} and optional - * {@link org.apache.http.HttpEntity entity}, and - * {@link org.apache.http.HttpConnection connections} - * over which messages are sent. In order to prepare messages - * before sending or after receiving, there are interceptors for - * {@link org.apache.http.HttpRequestInterceptor requests} and - * {@link org.apache.http.HttpResponseInterceptor responses}. - */ -package org.apache.http; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/params/HttpParamConfig.java b/lib/httpclient-android/src/main/java/org/apache/http/params/HttpParamConfig.java deleted file mode 100644 index 177bf569..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/params/HttpParamConfig.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.params; - -import java.nio.charset.Charset; - -import org.apache.http.config.ConnectionConfig; -import org.apache.http.config.MessageConstraints; -import org.apache.http.config.SocketConfig; - -/** - * @deprecated (4.3) provided for compatibility with {@link HttpParams}. Do not use. - * - * @since 4.3 - */ -@Deprecated -public final class HttpParamConfig { - - private HttpParamConfig() { - } - - public static SocketConfig getSocketConfig(final HttpParams params) { - return SocketConfig.custom() - .setSoTimeout(params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0)) - .setSoLinger(params.getIntParameter(CoreConnectionPNames.SO_LINGER, -1)) - .setTcpNoDelay(params.getBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)) - .build(); - } - - public static MessageConstraints getMessageConstraints(final HttpParams params) { - return MessageConstraints.custom() - .setMaxHeaderCount(params.getIntParameter(CoreConnectionPNames.MAX_HEADER_COUNT, -1)) - .setMaxLineLength(params.getIntParameter(CoreConnectionPNames.MAX_LINE_LENGTH, -1)) - .build(); - } - - public static ConnectionConfig getConnectionConfig(final HttpParams params) { - final MessageConstraints messageConstraints = getMessageConstraints(params); - final String csname = (String) params.getParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET); - return ConnectionConfig.custom() - .setCharset(csname != null ? Charset.forName(csname) : null) - .setMessageConstraints(messageConstraints) - .build(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/params/HttpParamsNames.java b/lib/httpclient-android/src/main/java/org/apache/http/params/HttpParamsNames.java deleted file mode 100644 index b2721d92..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/params/HttpParamsNames.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.params; - -import java.util.Set; - -/** - * Gives access to the full set of parameter names. - * - * @see HttpParams - * - * @since 4.2 - * - * @deprecated (4.3) use configuration classes provided 'org.apache.http.config' - * and 'org.apache.http.client.config' - */ -@Deprecated -public interface HttpParamsNames { - - /** - * Returns the current set of names; - * in the case of stacked parameters, returns the names - * from all the participating HttpParams instances. - * - * Changes to the underlying HttpParams are not reflected - * in the set - it is a snapshot. - * - * @return the names, as a Set - */ - Set getNames(); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/params/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/params/package-info.java deleted file mode 100644 index 0089dc9c..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/params/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Deprecated. - * @deprecated (4.3). - */ -package org.apache.http.params; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/pool/AbstractConnPool.java b/lib/httpclient-android/src/main/java/org/apache/http/pool/AbstractConnPool.java deleted file mode 100644 index a2c31030..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/pool/AbstractConnPool.java +++ /dev/null @@ -1,533 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.pool; - -import java.io.IOException; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.concurrent.FutureCallback; -import org.apache.http.util.Args; -import org.apache.http.util.Asserts; - -/** - * Abstract synchronous (blocking) pool of connections. - *

    - * Please note that this class does not maintain its own pool of execution {@link Thread}s. - * Therefore, one must call {@link Future#get()} or {@link Future#get(long, TimeUnit)} - * method on the {@link Future} object returned by the - * {@link #lease(Object, Object, FutureCallback)} method in order for the lease operation - * to complete. - * - * @param the route type that represents the opposite endpoint of a pooled - * connection. - * @param the connection type. - * @param the type of the pool entry containing a pooled connection. - * @since 4.2 - */ -@ThreadSafe -public abstract class AbstractConnPool> - implements ConnPool, ConnPoolControl { - - private final Lock lock; - private final ConnFactory connFactory; - private final Map> routeToPool; - private final Set leased; - private final LinkedList available; - private final LinkedList> pending; - private final Map maxPerRoute; - - private volatile boolean isShutDown; - private volatile int defaultMaxPerRoute; - private volatile int maxTotal; - - public AbstractConnPool( - final ConnFactory connFactory, - final int defaultMaxPerRoute, - final int maxTotal) { - super(); - this.connFactory = Args.notNull(connFactory, "Connection factory"); - this.defaultMaxPerRoute = Args.notNegative(defaultMaxPerRoute, "Max per route value"); - this.maxTotal = Args.notNegative(maxTotal, "Max total value"); - this.lock = new ReentrantLock(); - this.routeToPool = new HashMap>(); - this.leased = new HashSet(); - this.available = new LinkedList(); - this.pending = new LinkedList>(); - this.maxPerRoute = new HashMap(); - } - - /** - * Creates a new entry for the given connection with the given route. - */ - protected abstract E createEntry(T route, C conn); - - /** - * @since 4.3 - */ - protected void onLease(final E entry) { - } - - /** - * @since 4.3 - */ - protected void onRelease(final E entry) { - } - - public boolean isShutdown() { - return this.isShutDown; - } - - /** - * Shuts down the pool. - */ - public void shutdown() throws IOException { - if (this.isShutDown) { - return ; - } - this.isShutDown = true; - this.lock.lock(); - try { - for (final E entry: this.available) { - entry.close(); - } - for (final E entry: this.leased) { - entry.close(); - } - for (final RouteSpecificPool pool: this.routeToPool.values()) { - pool.shutdown(); - } - this.routeToPool.clear(); - this.leased.clear(); - this.available.clear(); - } finally { - this.lock.unlock(); - } - } - - private RouteSpecificPool getPool(final T route) { - RouteSpecificPool pool = this.routeToPool.get(route); - if (pool == null) { - pool = new RouteSpecificPool(route) { - - @Override - protected E createEntry(final C conn) { - return AbstractConnPool.this.createEntry(route, conn); - } - - }; - this.routeToPool.put(route, pool); - } - return pool; - } - - /** - * {@inheritDoc} - *

    - * Please note that this class does not maintain its own pool of execution - * {@link Thread}s. Therefore, one must call {@link Future#get()} - * or {@link Future#get(long, TimeUnit)} method on the {@link Future} - * returned by this method in order for the lease operation to complete. - */ - public Future lease(final T route, final Object state, final FutureCallback callback) { - Args.notNull(route, "Route"); - Asserts.check(!this.isShutDown, "Connection pool shut down"); - return new PoolEntryFuture(this.lock, callback) { - - @Override - public E getPoolEntry( - final long timeout, - final TimeUnit tunit) - throws InterruptedException, TimeoutException, IOException { - final E entry = getPoolEntryBlocking(route, state, timeout, tunit, this); - onLease(entry); - return entry; - } - - }; - } - - /** - * Attempts to lease a connection for the given route and with the given - * state from the pool. - *

    - * Please note that this class does not maintain its own pool of execution - * {@link Thread}s. Therefore, one must call {@link Future#get()} - * or {@link Future#get(long, TimeUnit)} method on the {@link Future} - * returned by this method in order for the lease operation to complete. - * - * @param route route of the connection. - * @param state arbitrary object that represents a particular state - * (usually a security principal or a unique token identifying - * the user whose credentials have been used while establishing the connection). - * May be null. - * @return future for a leased pool entry. - */ - public Future lease(final T route, final Object state) { - return lease(route, state, null); - } - - private E getPoolEntryBlocking( - final T route, final Object state, - final long timeout, final TimeUnit tunit, - final PoolEntryFuture future) - throws IOException, InterruptedException, TimeoutException { - - Date deadline = null; - if (timeout > 0) { - deadline = new Date - (System.currentTimeMillis() + tunit.toMillis(timeout)); - } - - this.lock.lock(); - try { - final RouteSpecificPool pool = getPool(route); - E entry = null; - while (entry == null) { - Asserts.check(!this.isShutDown, "Connection pool shut down"); - for (;;) { - entry = pool.getFree(state); - if (entry == null) { - break; - } - if (entry.isClosed() || entry.isExpired(System.currentTimeMillis())) { - entry.close(); - this.available.remove(entry); - pool.free(entry, false); - } else { - break; - } - } - if (entry != null) { - this.available.remove(entry); - this.leased.add(entry); - return entry; - } - - // New connection is needed - final int maxPerRoute = getMax(route); - // Shrink the pool prior to allocating a new connection - final int excess = Math.max(0, pool.getAllocatedCount() + 1 - maxPerRoute); - if (excess > 0) { - for (int i = 0; i < excess; i++) { - final E lastUsed = pool.getLastUsed(); - if (lastUsed == null) { - break; - } - lastUsed.close(); - this.available.remove(lastUsed); - pool.remove(lastUsed); - } - } - - if (pool.getAllocatedCount() < maxPerRoute) { - final int totalUsed = this.leased.size(); - final int freeCapacity = Math.max(this.maxTotal - totalUsed, 0); - if (freeCapacity > 0) { - final int totalAvailable = this.available.size(); - if (totalAvailable > freeCapacity - 1) { - if (!this.available.isEmpty()) { - final E lastUsed = this.available.removeLast(); - lastUsed.close(); - final RouteSpecificPool otherpool = getPool(lastUsed.getRoute()); - otherpool.remove(lastUsed); - } - } - final C conn = this.connFactory.create(route); - entry = pool.add(conn); - this.leased.add(entry); - return entry; - } - } - - boolean success = false; - try { - pool.queue(future); - this.pending.add(future); - success = future.await(deadline); - } finally { - // In case of 'success', we were woken up by the - // connection pool and should now have a connection - // waiting for us, or else we're shutting down. - // Just continue in the loop, both cases are checked. - pool.unqueue(future); - this.pending.remove(future); - } - // check for spurious wakeup vs. timeout - if (!success && (deadline != null) && - (deadline.getTime() <= System.currentTimeMillis())) { - break; - } - } - throw new TimeoutException("Timeout waiting for connection"); - } finally { - this.lock.unlock(); - } - } - - public void release(final E entry, final boolean reusable) { - this.lock.lock(); - try { - if (this.leased.remove(entry)) { - final RouteSpecificPool pool = getPool(entry.getRoute()); - pool.free(entry, reusable); - if (reusable && !this.isShutDown) { - this.available.addFirst(entry); - onRelease(entry); - } else { - entry.close(); - } - PoolEntryFuture future = pool.nextPending(); - if (future != null) { - this.pending.remove(future); - } else { - future = this.pending.poll(); - } - if (future != null) { - future.wakeup(); - } - } - } finally { - this.lock.unlock(); - } - } - - private int getMax(final T route) { - final Integer v = this.maxPerRoute.get(route); - if (v != null) { - return v.intValue(); - } else { - return this.defaultMaxPerRoute; - } - } - - public void setMaxTotal(final int max) { - Args.notNegative(max, "Max value"); - this.lock.lock(); - try { - this.maxTotal = max; - } finally { - this.lock.unlock(); - } - } - - public int getMaxTotal() { - this.lock.lock(); - try { - return this.maxTotal; - } finally { - this.lock.unlock(); - } - } - - public void setDefaultMaxPerRoute(final int max) { - Args.notNegative(max, "Max per route value"); - this.lock.lock(); - try { - this.defaultMaxPerRoute = max; - } finally { - this.lock.unlock(); - } - } - - public int getDefaultMaxPerRoute() { - this.lock.lock(); - try { - return this.defaultMaxPerRoute; - } finally { - this.lock.unlock(); - } - } - - public void setMaxPerRoute(final T route, final int max) { - Args.notNull(route, "Route"); - Args.notNegative(max, "Max per route value"); - this.lock.lock(); - try { - this.maxPerRoute.put(route, Integer.valueOf(max)); - } finally { - this.lock.unlock(); - } - } - - public int getMaxPerRoute(final T route) { - Args.notNull(route, "Route"); - this.lock.lock(); - try { - return getMax(route); - } finally { - this.lock.unlock(); - } - } - - public PoolStats getTotalStats() { - this.lock.lock(); - try { - return new PoolStats( - this.leased.size(), - this.pending.size(), - this.available.size(), - this.maxTotal); - } finally { - this.lock.unlock(); - } - } - - public PoolStats getStats(final T route) { - Args.notNull(route, "Route"); - this.lock.lock(); - try { - final RouteSpecificPool pool = getPool(route); - return new PoolStats( - pool.getLeasedCount(), - pool.getPendingCount(), - pool.getAvailableCount(), - getMax(route)); - } finally { - this.lock.unlock(); - } - } - - /** - * Enumerates all available connections. - * - * @since 4.3 - */ - protected void enumAvailable(final PoolEntryCallback callback) { - this.lock.lock(); - try { - final Iterator it = this.available.iterator(); - while (it.hasNext()) { - final E entry = it.next(); - callback.process(entry); - if (entry.isClosed()) { - final RouteSpecificPool pool = getPool(entry.getRoute()); - pool.remove(entry); - it.remove(); - } - } - purgePoolMap(); - } finally { - this.lock.unlock(); - } - } - - /** - * Enumerates all leased connections. - * - * @since 4.3 - */ - protected void enumLeased(final PoolEntryCallback callback) { - this.lock.lock(); - try { - final Iterator it = this.leased.iterator(); - while (it.hasNext()) { - final E entry = it.next(); - callback.process(entry); - } - } finally { - this.lock.unlock(); - } - } - - private void purgePoolMap() { - final Iterator>> it = this.routeToPool.entrySet().iterator(); - while (it.hasNext()) { - final Map.Entry> entry = it.next(); - final RouteSpecificPool pool = entry.getValue(); - if (pool.getPendingCount() + pool.getAllocatedCount() == 0) { - it.remove(); - } - } - } - - /** - * Closes connections that have been idle longer than the given period - * of time and evicts them from the pool. - * - * @param idletime maximum idle time. - * @param tunit time unit. - */ - public void closeIdle(final long idletime, final TimeUnit tunit) { - Args.notNull(tunit, "Time unit"); - long time = tunit.toMillis(idletime); - if (time < 0) { - time = 0; - } - final long deadline = System.currentTimeMillis() - time; - enumAvailable(new PoolEntryCallback() { - - public void process(final PoolEntry entry) { - if (entry.getUpdated() <= deadline) { - entry.close(); - } - } - - }); - } - - /** - * Closes expired connections and evicts them from the pool. - */ - public void closeExpired() { - final long now = System.currentTimeMillis(); - enumAvailable(new PoolEntryCallback() { - - public void process(final PoolEntry entry) { - if (entry.isExpired(now)) { - entry.close(); - } - } - - }); - } - - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append("[leased: "); - buffer.append(this.leased); - buffer.append("][available: "); - buffer.append(this.available); - buffer.append("][pending: "); - buffer.append(this.pending); - buffer.append("]"); - return buffer.toString(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/pool/ConnFactory.java b/lib/httpclient-android/src/main/java/org/apache/http/pool/ConnFactory.java deleted file mode 100644 index faca9960..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/pool/ConnFactory.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.pool; - -import java.io.IOException; - -/** - * Factory for poolable blocking connections. - * - * @param the route type that represents the opposite endpoint of a pooled - * connection. - * @param the connection type. - * @since 4.2 - */ -public interface ConnFactory { - - C create(T route) throws IOException; - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/pool/ConnPool.java b/lib/httpclient-android/src/main/java/org/apache/http/pool/ConnPool.java deleted file mode 100644 index f04cae9a..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/pool/ConnPool.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.pool; - -import java.util.concurrent.Future; - -import org.apache.http.concurrent.FutureCallback; - -/** - * ConnPool represents a shared pool connections can be leased from - * and released back to. - * - * @param the route type that represents the opposite endpoint of a pooled - * connection. - * @param the type of the pool entry containing a pooled connection. - * @since 4.2 - */ -public interface ConnPool { - - /** - * Attempts to lease a connection for the given route and with the given - * state from the pool. - * - * @param route route of the connection. - * @param state arbitrary object that represents a particular state - * (usually a security principal or a unique token identifying - * the user whose credentials have been used while establishing the connection). - * May be null. - * @param callback operation completion callback. - * - * @return future for a leased pool entry. - */ - Future lease(final T route, final Object state, final FutureCallback callback); - - /** - * Releases the pool entry back to the pool. - * - * @param entry pool entry leased from the pool - * @param reusable flag indicating whether or not the released connection - * is in a consistent state and is safe for further use. - */ - void release(E entry, boolean reusable); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/pool/ConnPoolControl.java b/lib/httpclient-android/src/main/java/org/apache/http/pool/ConnPoolControl.java deleted file mode 100644 index 38738416..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/pool/ConnPoolControl.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.pool; - -/** - * Interface to control runtime properties of a {@link ConnPool} such as - * maximum total number of connections or maximum connections per route - * allowed. - * - * @param the route type that represents the opposite endpoint of a pooled - * connection. - * @since 4.2 - */ -public interface ConnPoolControl { - - void setMaxTotal(int max); - - int getMaxTotal(); - - void setDefaultMaxPerRoute(int max); - - int getDefaultMaxPerRoute(); - - void setMaxPerRoute(final T route, int max); - - int getMaxPerRoute(final T route); - - PoolStats getTotalStats(); - - PoolStats getStats(final T route); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/pool/PoolEntry.java b/lib/httpclient-android/src/main/java/org/apache/http/pool/PoolEntry.java deleted file mode 100644 index e01f8b47..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/pool/PoolEntry.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.pool; - -import java.util.concurrent.TimeUnit; - -import org.apache.http.annotation.GuardedBy; -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.util.Args; - -/** - * Pool entry containing a pool connection object along with its route. - *

    - * The connection contained by the pool entry may have an expiration time which - * can be either set upon construction time or updated with - * the {@link #updateExpiry(long, TimeUnit)}. - *

    - * Pool entry may also have an object associated with it that represents - * a connection state (usually a security principal or a unique token identifying - * the user whose credentials have been used while establishing the connection). - * - * @param the route type that represents the opposite endpoint of a pooled - * connection. - * @param the connection type. - * @since 4.2 - */ -@ThreadSafe -public abstract class PoolEntry { - - private final String id; - private final T route; - private final C conn; - private final long created; - private final long validUnit; - - @GuardedBy("this") - private long updated; - - @GuardedBy("this") - private long expiry; - - private volatile Object state; - - /** - * Creates new PoolEntry instance. - * - * @param id unique identifier of the pool entry. May be null. - * @param route route to the opposite endpoint. - * @param conn the connection. - * @param timeToLive maximum time to live. May be zero if the connection - * does not have an expiry deadline. - * @param tunit time unit. - */ - public PoolEntry(final String id, final T route, final C conn, - final long timeToLive, final TimeUnit tunit) { - super(); - Args.notNull(route, "Route"); - Args.notNull(conn, "Connection"); - Args.notNull(tunit, "Time unit"); - this.id = id; - this.route = route; - this.conn = conn; - this.created = System.currentTimeMillis(); - if (timeToLive > 0) { - this.validUnit = this.created + tunit.toMillis(timeToLive); - } else { - this.validUnit = Long.MAX_VALUE; - } - this.expiry = this.validUnit; - } - - /** - * Creates new PoolEntry instance without an expiry deadline. - * - * @param id unique identifier of the pool entry. May be null. - * @param route route to the opposite endpoint. - * @param conn the connection. - */ - public PoolEntry(final String id, final T route, final C conn) { - this(id, route, conn, 0, TimeUnit.MILLISECONDS); - } - - public String getId() { - return this.id; - } - - public T getRoute() { - return this.route; - } - - public C getConnection() { - return this.conn; - } - - public long getCreated() { - return this.created; - } - - public long getValidUnit() { - return this.validUnit; - } - - public Object getState() { - return this.state; - } - - public void setState(final Object state) { - this.state = state; - } - - public synchronized long getUpdated() { - return this.updated; - } - - public synchronized long getExpiry() { - return this.expiry; - } - - public synchronized void updateExpiry(final long time, final TimeUnit tunit) { - Args.notNull(tunit, "Time unit"); - this.updated = System.currentTimeMillis(); - final long newExpiry; - if (time > 0) { - newExpiry = this.updated + tunit.toMillis(time); - } else { - newExpiry = Long.MAX_VALUE; - } - this.expiry = Math.min(newExpiry, this.validUnit); - } - - public synchronized boolean isExpired(final long now) { - return now >= this.expiry; - } - - /** - * Invalidates the pool entry and closes the pooled connection associated - * with it. - */ - public abstract void close(); - - /** - * Returns true if the pool entry has been invalidated. - */ - public abstract boolean isClosed(); - - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append("[id:"); - buffer.append(this.id); - buffer.append("][route:"); - buffer.append(this.route); - buffer.append("][state:"); - buffer.append(this.state); - buffer.append("]"); - return buffer.toString(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/pool/PoolEntryCallback.java b/lib/httpclient-android/src/main/java/org/apache/http/pool/PoolEntryCallback.java deleted file mode 100644 index 07dbcb08..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/pool/PoolEntryCallback.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.pool; - -/** - * Pool entry callabck. - * - * @param the route type that represents the opposite endpoint of a pooled - * connection. - * @param the connection type. - * @since 4.3 - */ -public interface PoolEntryCallback { - - void process(PoolEntry entry); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/pool/PoolEntryFuture.java b/lib/httpclient-android/src/main/java/org/apache/http/pool/PoolEntryFuture.java deleted file mode 100644 index 8979a11f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/pool/PoolEntryFuture.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.pool; - -import java.io.IOException; -import java.util.Date; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; - -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.concurrent.FutureCallback; -import org.apache.http.util.Args; - -@ThreadSafe -abstract class PoolEntryFuture implements Future { - - private final Lock lock; - private final FutureCallback callback; - private final Condition condition; - private volatile boolean cancelled; - private volatile boolean completed; - private T result; - - PoolEntryFuture(final Lock lock, final FutureCallback callback) { - super(); - this.lock = lock; - this.condition = lock.newCondition(); - this.callback = callback; - } - - public boolean cancel(final boolean mayInterruptIfRunning) { - this.lock.lock(); - try { - if (this.completed) { - return false; - } - this.completed = true; - this.cancelled = true; - if (this.callback != null) { - this.callback.cancelled(); - } - this.condition.signalAll(); - return true; - } finally { - this.lock.unlock(); - } - } - - public boolean isCancelled() { - return this.cancelled; - } - - public boolean isDone() { - return this.completed; - } - - public T get() throws InterruptedException, ExecutionException { - try { - return get(0, TimeUnit.MILLISECONDS); - } catch (final TimeoutException ex) { - throw new ExecutionException(ex); - } - } - - public T get( - final long timeout, - final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { - Args.notNull(unit, "Time unit"); - this.lock.lock(); - try { - if (this.completed) { - return this.result; - } - this.result = getPoolEntry(timeout, unit); - this.completed = true; - if (this.callback != null) { - this.callback.completed(this.result); - } - return result; - } catch (final IOException ex) { - this.completed = true; - this.result = null; - if (this.callback != null) { - this.callback.failed(ex); - } - throw new ExecutionException(ex); - } finally { - this.lock.unlock(); - } - } - - protected abstract T getPoolEntry( - long timeout, TimeUnit unit) throws IOException, InterruptedException, TimeoutException; - - public boolean await(final Date deadline) throws InterruptedException { - this.lock.lock(); - try { - if (this.cancelled) { - throw new InterruptedException("Operation interrupted"); - } - final boolean success; - if (deadline != null) { - success = this.condition.awaitUntil(deadline); - } else { - this.condition.await(); - success = true; - } - if (this.cancelled) { - throw new InterruptedException("Operation interrupted"); - } - return success; - } finally { - this.lock.unlock(); - } - - } - - public void wakeup() { - this.lock.lock(); - try { - this.condition.signalAll(); - } finally { - this.lock.unlock(); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/pool/PoolStats.java b/lib/httpclient-android/src/main/java/org/apache/http/pool/PoolStats.java deleted file mode 100644 index a3260cc3..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/pool/PoolStats.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.pool; - -import org.apache.http.annotation.Immutable; - -/** - * Pool statistics. - *

    - * The total number of connections in the pool is equal to {@code available} plus {@code leased}. - *

    - * - * @since 4.2 - */ -@Immutable -public class PoolStats { - - private final int leased; - private final int pending; - private final int available; - private final int max; - - public PoolStats(final int leased, final int pending, final int free, final int max) { - super(); - this.leased = leased; - this.pending = pending; - this.available = free; - this.max = max; - } - - /** - * Gets the number of persistent connections tracked by the connection manager currently being used to execute - * requests. - *

    - * The total number of connections in the pool is equal to {@code available} plus {@code leased}. - *

    - * - * @return the number of persistent connections. - */ - public int getLeased() { - return this.leased; - } - - /** - * Gets the number of connection requests being blocked awaiting a free connection. This can happen only if there - * are more worker threads contending for fewer connections. - * - * @return the number of connection requests being blocked awaiting a free connection. - */ - public int getPending() { - return this.pending; - } - - /** - * Gets the number idle persistent connections. - *

    - * The total number of connections in the pool is equal to {@code available} plus {@code leased}. - *

    - * - * @return number idle persistent connections. - */ - public int getAvailable() { - return this.available; - } - - /** - * Gets the maximum number of allowed persistent connections. - * - * @return the maximum number of allowed persistent connections. - */ - public int getMax() { - return this.max; - } - - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append("[leased: "); - buffer.append(this.leased); - buffer.append("; pending: "); - buffer.append(this.pending); - buffer.append("; available: "); - buffer.append(this.available); - buffer.append("; max: "); - buffer.append(this.max); - buffer.append("]"); - return buffer.toString(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/pool/RouteSpecificPool.java b/lib/httpclient-android/src/main/java/org/apache/http/pool/RouteSpecificPool.java deleted file mode 100644 index f560e0dd..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/pool/RouteSpecificPool.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.pool; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Set; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.util.Args; -import org.apache.http.util.Asserts; - -@NotThreadSafe -abstract class RouteSpecificPool> { - - private final T route; - private final Set leased; - private final LinkedList available; - private final LinkedList> pending; - - RouteSpecificPool(final T route) { - super(); - this.route = route; - this.leased = new HashSet(); - this.available = new LinkedList(); - this.pending = new LinkedList>(); - } - - protected abstract E createEntry(C conn); - - public final T getRoute() { - return route; - } - - public int getLeasedCount() { - return this.leased.size(); - } - - public int getPendingCount() { - return this.pending.size(); - } - - public int getAvailableCount() { - return this.available.size(); - } - - public int getAllocatedCount() { - return this.available.size() + this.leased.size(); - } - - public E getFree(final Object state) { - if (!this.available.isEmpty()) { - if (state != null) { - final Iterator it = this.available.iterator(); - while (it.hasNext()) { - final E entry = it.next(); - if (state.equals(entry.getState())) { - it.remove(); - this.leased.add(entry); - return entry; - } - } - } - final Iterator it = this.available.iterator(); - while (it.hasNext()) { - final E entry = it.next(); - if (entry.getState() == null) { - it.remove(); - this.leased.add(entry); - return entry; - } - } - } - return null; - } - - public E getLastUsed() { - if (!this.available.isEmpty()) { - return this.available.getLast(); - } else { - return null; - } - } - - public boolean remove(final E entry) { - Args.notNull(entry, "Pool entry"); - if (!this.available.remove(entry)) { - if (!this.leased.remove(entry)) { - return false; - } - } - return true; - } - - public void free(final E entry, final boolean reusable) { - Args.notNull(entry, "Pool entry"); - final boolean found = this.leased.remove(entry); - Asserts.check(found, "Entry %s has not been leased from this pool", entry); - if (reusable) { - this.available.addFirst(entry); - } - } - - public E add(final C conn) { - final E entry = createEntry(conn); - this.leased.add(entry); - return entry; - } - - public void queue(final PoolEntryFuture future) { - if (future == null) { - return; - } - this.pending.add(future); - } - - public PoolEntryFuture nextPending() { - return this.pending.poll(); - } - - public void unqueue(final PoolEntryFuture future) { - if (future == null) { - return; - } - - this.pending.remove(future); - } - - public void shutdown() { - for (final PoolEntryFuture future: this.pending) { - future.cancel(true); - } - this.pending.clear(); - for (final E entry: this.available) { - entry.close(); - } - this.available.clear(); - for (final E entry: this.leased) { - entry.close(); - } - this.leased.clear(); - } - - @Override - public String toString() { - final StringBuilder buffer = new StringBuilder(); - buffer.append("[route: "); - buffer.append(this.route); - buffer.append("][leased: "); - buffer.append(this.leased.size()); - buffer.append("][available: "); - buffer.append(this.available.size()); - buffer.append("][pending: "); - buffer.append(this.pending.size()); - buffer.append("]"); - return buffer.toString(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/pool/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/pool/package-info.java deleted file mode 100644 index b832135a..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/pool/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Client side connection pools APIs for synchronous, blocking - * communication. - */ -package org.apache.http.pool; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/protocol/BasicHttpContextHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/protocol/BasicHttpContextHC4.java deleted file mode 100644 index b8aabd3d..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/protocol/BasicHttpContextHC4.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.protocol; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.util.Args; - -/** - * Default implementation of {@link HttpContext}. - *

    - * Please note instances of this class can be thread unsafe if the - * parent context is not thread safe. - * - * @since 4.0 - */ -@ThreadSafe -public class BasicHttpContextHC4 implements HttpContext { - - private final HttpContext parentContext; - private final Map map; - - public BasicHttpContextHC4() { - this(null); - } - - public BasicHttpContextHC4(final HttpContext parentContext) { - super(); - this.map = new ConcurrentHashMap(); - this.parentContext = parentContext; - } - - public Object getAttribute(final String id) { - Args.notNull(id, "Id"); - Object obj = this.map.get(id); - if (obj == null && this.parentContext != null) { - obj = this.parentContext.getAttribute(id); - } - return obj; - } - - public void setAttribute(final String id, final Object obj) { - Args.notNull(id, "Id"); - if (obj != null) { - this.map.put(id, obj); - } else { - this.map.remove(id); - } - } - - public Object removeAttribute(final String id) { - Args.notNull(id, "Id"); - return this.map.remove(id); - } - - /** - * @since 4.2 - */ - public void clear() { - this.map.clear(); - } - - @Override - public String toString() { - return this.map.toString(); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/protocol/ChainBuilder.java b/lib/httpclient-android/src/main/java/org/apache/http/protocol/ChainBuilder.java deleted file mode 100644 index c1ca4dde..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/protocol/ChainBuilder.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.protocol; - -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; - -import org.apache.http.annotation.NotThreadSafe; - -/** - * Builder class to build a linked list (chain) of unique class instances. Each class can have - * only one instance in the list. Useful for building lists of protocol interceptors. - * - * @see ImmutableHttpProcessor - * - * @since 4.3 - */ -@NotThreadSafe -final class ChainBuilder { - - private final LinkedList list; - private final Map, E> uniqueClasses; - - public ChainBuilder() { - this.list = new LinkedList(); - this.uniqueClasses = new HashMap, E>(); - } - - private void ensureUnique(final E e) { - final E previous = this.uniqueClasses.remove(e.getClass()); - if (previous != null) { - this.list.remove(previous); - } - this.uniqueClasses.put(e.getClass(), e); - } - - public ChainBuilder addFirst(final E e) { - if (e == null) { - return this; - } - ensureUnique(e); - this.list.addFirst(e); - return this; - } - - public ChainBuilder addLast(final E e) { - if (e == null) { - return this; - } - ensureUnique(e); - this.list.addLast(e); - return this; - } - - public ChainBuilder addAllFirst(final Collection c) { - if (c == null) { - return this; - } - for (final E e: c) { - addFirst(e); - } - return this; - } - - public ChainBuilder addAllFirst(final E... c) { - if (c == null) { - return this; - } - for (final E e: c) { - addFirst(e); - } - return this; - } - - public ChainBuilder addAllLast(final Collection c) { - if (c == null) { - return this; - } - for (final E e: c) { - addLast(e); - } - return this; - } - - public ChainBuilder addAllLast(final E... c) { - if (c == null) { - return this; - } - for (final E e: c) { - addLast(e); - } - return this; - } - - public LinkedList build() { - return new LinkedList(this.list); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/protocol/HttpCoreContext.java b/lib/httpclient-android/src/main/java/org/apache/http/protocol/HttpCoreContext.java deleted file mode 100644 index 7dcce05c..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/protocol/HttpCoreContext.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.protocol; - -import org.apache.http.HttpConnection; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.util.Args; - -/** - * Implementation of {@link HttpContext} that provides convenience - * setters for user assignable attributes and getter for readable attributes. - * - * @since 4.3 - */ -@NotThreadSafe -public class HttpCoreContext implements HttpContext { - - /** - * Attribute name of a {@link org.apache.http.HttpConnection} object that - * represents the actual HTTP connection. - */ - public static final String HTTP_CONNECTION = "http.connection"; - - /** - * Attribute name of a {@link org.apache.http.HttpRequest} object that - * represents the actual HTTP request. - */ - public static final String HTTP_REQUEST = "http.request"; - - /** - * Attribute name of a {@link org.apache.http.HttpResponse} object that - * represents the actual HTTP response. - */ - public static final String HTTP_RESPONSE = "http.response"; - - /** - * Attribute name of a {@link org.apache.http.HttpHost} object that - * represents the connection target. - */ - public static final String HTTP_TARGET_HOST = "http.target_host"; - - /** - * Attribute name of a {@link Boolean} object that represents the - * the flag indicating whether the actual request has been fully transmitted - * to the target host. - */ - public static final String HTTP_REQ_SENT = "http.request_sent"; - - public static HttpCoreContext create() { - return new HttpCoreContext(new BasicHttpContextHC4()); - } - - public static HttpCoreContext adapt(final HttpContext context) { - Args.notNull(context, "HTTP context"); - if (context instanceof HttpCoreContext) { - return (HttpCoreContext) context; - } else { - return new HttpCoreContext(context); - } - } - - private final HttpContext context; - - public HttpCoreContext(final HttpContext context) { - super(); - this.context = context; - } - - public HttpCoreContext() { - super(); - this.context = new BasicHttpContextHC4(); - } - - public Object getAttribute(final String id) { - return context.getAttribute(id); - } - - public void setAttribute(final String id, final Object obj) { - context.setAttribute(id, obj); - } - - public Object removeAttribute(final String id) { - return context.removeAttribute(id); - } - - public T getAttribute(final String attribname, final Class clazz) { - Args.notNull(clazz, "Attribute class"); - final Object obj = getAttribute(attribname); - if (obj == null) { - return null; - } - return clazz.cast(obj); - } - - public T getConnection(final Class clazz) { - return getAttribute(HTTP_CONNECTION, clazz); - } - - public HttpConnection getConnection() { - return getAttribute(HTTP_CONNECTION, HttpConnection.class); - } - - public HttpRequest getRequest() { - return getAttribute(HTTP_REQUEST, HttpRequest.class); - } - - public boolean isRequestSent() { - final Boolean b = getAttribute(HTTP_REQ_SENT, Boolean.class); - return b != null && b.booleanValue(); - } - - public HttpResponse getResponse() { - return getAttribute(HTTP_RESPONSE, HttpResponse.class); - } - - public void setTargetHost(final HttpHost host) { - setAttribute(HTTP_TARGET_HOST, host); - } - - public HttpHost getTargetHost() { - return getAttribute(HTTP_TARGET_HOST, HttpHost.class); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/protocol/HttpProcessorBuilder.java b/lib/httpclient-android/src/main/java/org/apache/http/protocol/HttpProcessorBuilder.java deleted file mode 100644 index 5e5627dd..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/protocol/HttpProcessorBuilder.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.protocol; - -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.HttpResponseInterceptor; - -/** - * Builder for {@link HttpProcessor} instances. - * - * @since 4.3 - */ -public class HttpProcessorBuilder { - - private ChainBuilder requestChainBuilder; - private ChainBuilder responseChainBuilder; - - public static HttpProcessorBuilder create() { - return new HttpProcessorBuilder(); - } - - HttpProcessorBuilder() { - super(); - } - - private ChainBuilder getRequestChainBuilder() { - if (requestChainBuilder == null) { - requestChainBuilder = new ChainBuilder(); - } - return requestChainBuilder; - } - - private ChainBuilder getResponseChainBuilder() { - if (responseChainBuilder == null) { - responseChainBuilder = new ChainBuilder(); - } - return responseChainBuilder; - } - - public HttpProcessorBuilder addFirst(final HttpRequestInterceptor e) { - if (e == null) { - return this; - } - getRequestChainBuilder().addFirst(e); - return this; - } - - public HttpProcessorBuilder addLast(final HttpRequestInterceptor e) { - if (e == null) { - return this; - } - getRequestChainBuilder().addLast(e); - return this; - } - - public HttpProcessorBuilder add(final HttpRequestInterceptor e) { - return addLast(e); - } - - public HttpProcessorBuilder addAllFirst(final HttpRequestInterceptor... e) { - if (e == null) { - return this; - } - getRequestChainBuilder().addAllFirst(e); - return this; - } - - public HttpProcessorBuilder addAllLast(final HttpRequestInterceptor... e) { - if (e == null) { - return this; - } - getRequestChainBuilder().addAllLast(e); - return this; - } - - public HttpProcessorBuilder addAll(final HttpRequestInterceptor... e) { - return addAllLast(e); - } - - public HttpProcessorBuilder addFirst(final HttpResponseInterceptor e) { - if (e == null) { - return this; - } - getResponseChainBuilder().addFirst(e); - return this; - } - - public HttpProcessorBuilder addLast(final HttpResponseInterceptor e) { - if (e == null) { - return this; - } - getResponseChainBuilder().addLast(e); - return this; - } - - public HttpProcessorBuilder add(final HttpResponseInterceptor e) { - return addLast(e); - } - - public HttpProcessorBuilder addAllFirst(final HttpResponseInterceptor... e) { - if (e == null) { - return this; - } - getResponseChainBuilder().addAllFirst(e); - return this; - } - - public HttpProcessorBuilder addAllLast(final HttpResponseInterceptor... e) { - if (e == null) { - return this; - } - getResponseChainBuilder().addAllLast(e); - return this; - } - - public HttpProcessorBuilder addAll(final HttpResponseInterceptor... e) { - return addAllLast(e); - } - - public HttpProcessor build() { - return new ImmutableHttpProcessor( - requestChainBuilder != null ? requestChainBuilder.build() : null, - responseChainBuilder != null ? responseChainBuilder.build() : null); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/protocol/HttpRequestHandlerMapper.java b/lib/httpclient-android/src/main/java/org/apache/http/protocol/HttpRequestHandlerMapper.java deleted file mode 100644 index 2cd5f10f..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/protocol/HttpRequestHandlerMapper.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.protocol; - -import org.apache.http.HttpRequest; - -/** - * HttpRequestHandlerMapper can be used to resolve an instance of - * {@link HttpRequestHandler} matching a particular {@link HttpRequest}. Usually the - * mapped request handler will be used to process the request. - * - * @since 4.3 - */ -public interface HttpRequestHandlerMapper { - - /** - * Looks up a handler matching the given request. - * - * @param request the request to map to a handler - * @return HTTP request handler or null if no match - * is found. - */ - HttpRequestHandler lookup(HttpRequest request); - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/protocol/ImmutableHttpProcessor.java b/lib/httpclient-android/src/main/java/org/apache/http/protocol/ImmutableHttpProcessor.java deleted file mode 100644 index 661c339d..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/protocol/ImmutableHttpProcessor.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.protocol; - -import java.io.IOException; -import java.util.List; - -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.HttpResponse; -import org.apache.http.HttpResponseInterceptor; -import org.apache.http.annotation.ThreadSafe; - -/** - * Immutable {@link HttpProcessor}. - * - * @since 4.1 - */ -@ThreadSafe // provided injected dependencies are immutable -public final class ImmutableHttpProcessor implements HttpProcessor { - - private final HttpRequestInterceptor[] requestInterceptors; - private final HttpResponseInterceptor[] responseInterceptors; - - public ImmutableHttpProcessor( - final HttpRequestInterceptor[] requestInterceptors, - final HttpResponseInterceptor[] responseInterceptors) { - super(); - if (requestInterceptors != null) { - final int l = requestInterceptors.length; - this.requestInterceptors = new HttpRequestInterceptor[l]; - System.arraycopy(requestInterceptors, 0, this.requestInterceptors, 0, l); - } else { - this.requestInterceptors = new HttpRequestInterceptor[0]; - } - if (responseInterceptors != null) { - final int l = responseInterceptors.length; - this.responseInterceptors = new HttpResponseInterceptor[l]; - System.arraycopy(responseInterceptors, 0, this.responseInterceptors, 0, l); - } else { - this.responseInterceptors = new HttpResponseInterceptor[0]; - } - } - - /** - * @since 4.3 - */ - public ImmutableHttpProcessor( - final List requestInterceptors, - final List responseInterceptors) { - super(); - if (requestInterceptors != null) { - final int l = requestInterceptors.size(); - this.requestInterceptors = requestInterceptors.toArray(new HttpRequestInterceptor[l]); - } else { - this.requestInterceptors = new HttpRequestInterceptor[0]; - } - if (responseInterceptors != null) { - final int l = responseInterceptors.size(); - this.responseInterceptors = responseInterceptors.toArray(new HttpResponseInterceptor[l]); - } else { - this.responseInterceptors = new HttpResponseInterceptor[0]; - } - } - - /** - * @deprecated (4.3) do not use. - */ - @Deprecated - public ImmutableHttpProcessor( - final HttpRequestInterceptorList requestInterceptors, - final HttpResponseInterceptorList responseInterceptors) { - super(); - if (requestInterceptors != null) { - final int count = requestInterceptors.getRequestInterceptorCount(); - this.requestInterceptors = new HttpRequestInterceptor[count]; - for (int i = 0; i < count; i++) { - this.requestInterceptors[i] = requestInterceptors.getRequestInterceptor(i); - } - } else { - this.requestInterceptors = new HttpRequestInterceptor[0]; - } - if (responseInterceptors != null) { - final int count = responseInterceptors.getResponseInterceptorCount(); - this.responseInterceptors = new HttpResponseInterceptor[count]; - for (int i = 0; i < count; i++) { - this.responseInterceptors[i] = responseInterceptors.getResponseInterceptor(i); - } - } else { - this.responseInterceptors = new HttpResponseInterceptor[0]; - } - } - - public ImmutableHttpProcessor(final HttpRequestInterceptor... requestInterceptors) { - this(requestInterceptors, null); - } - - public ImmutableHttpProcessor(final HttpResponseInterceptor... responseInterceptors) { - this(null, responseInterceptors); - } - - public void process( - final HttpRequest request, - final HttpContext context) throws IOException, HttpException { - for (final HttpRequestInterceptor requestInterceptor : this.requestInterceptors) { - requestInterceptor.process(request, context); - } - } - - public void process( - final HttpResponse response, - final HttpContext context) throws IOException, HttpException { - for (final HttpResponseInterceptor responseInterceptor : this.responseInterceptors) { - responseInterceptor.process(response, context); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/protocol/RequestConnControlHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/protocol/RequestConnControlHC4.java deleted file mode 100644 index 8a39132c..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/protocol/RequestConnControlHC4.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.protocol; - -import java.io.IOException; - -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.annotation.Immutable; -import org.apache.http.util.Args; - -/** - * RequestConnControlHC4 is responsible for adding Connection header - * to the outgoing requests, which is essential for managing persistence of - * HTTP/1.0 connections. This interceptor is recommended for - * client side protocol processors. - * - * @since 4.0 - */ -@Immutable -public class RequestConnControlHC4 implements HttpRequestInterceptor { - - public RequestConnControlHC4() { - super(); - } - - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - - final String method = request.getRequestLine().getMethod(); - if (method.equalsIgnoreCase("CONNECT")) { - return; - } - - if (!request.containsHeader(HTTP.CONN_DIRECTIVE)) { - // Default policy is to keep connection alive - // whenever possible - request.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/protocol/RequestContentHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/protocol/RequestContentHC4.java deleted file mode 100644 index 826618be..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/protocol/RequestContentHC4.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.protocol; - -import java.io.IOException; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.HttpVersion; -import org.apache.http.ProtocolException; -import org.apache.http.ProtocolVersion; -import org.apache.http.annotation.Immutable; -import org.apache.http.util.Args; - -/** - * RequestContentHC4 is the most important interceptor for outgoing requests. - * It is responsible for delimiting content length by adding - * Content-Length or Transfer-Content headers based - * on the properties of the enclosed entity and the protocol version. - * This interceptor is required for correct functioning of client side protocol - * processors. - * - * @since 4.0 - */ -@Immutable -public class RequestContentHC4 implements HttpRequestInterceptor { - - private final boolean overwrite; - - /** - * Default constructor. The Content-Length or Transfer-Encoding - * will cause the interceptor to throw {@link ProtocolException} if already present in the - * response message. - */ - public RequestContentHC4() { - this(false); - } - - /** - * Constructor that can be used to fine-tune behavior of this interceptor. - * - * @param overwrite If set to true the Content-Length and - * Transfer-Encoding headers will be created or updated if already present. - * If set to false the Content-Length and - * Transfer-Encoding headers will cause the interceptor to throw - * {@link ProtocolException} if already present in the response message. - * - * @since 4.2 - */ - public RequestContentHC4(final boolean overwrite) { - super(); - this.overwrite = overwrite; - } - - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - if (request instanceof HttpEntityEnclosingRequest) { - if (this.overwrite) { - request.removeHeaders(HTTP.TRANSFER_ENCODING); - request.removeHeaders(HTTP.CONTENT_LEN); - } else { - if (request.containsHeader(HTTP.TRANSFER_ENCODING)) { - throw new ProtocolException("Transfer-encoding header already present"); - } - if (request.containsHeader(HTTP.CONTENT_LEN)) { - throw new ProtocolException("Content-Length header already present"); - } - } - final ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); - final HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity(); - if (entity == null) { - request.addHeader(HTTP.CONTENT_LEN, "0"); - return; - } - // Must specify a transfer encoding or a content length - if (entity.isChunked() || entity.getContentLength() < 0) { - if (ver.lessEquals(HttpVersion.HTTP_1_0)) { - throw new ProtocolException( - "Chunked transfer encoding not allowed for " + ver); - } - request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING); - } else { - request.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength())); - } - // Specify a content type if known - if (entity.getContentType() != null && !request.containsHeader( - HTTP.CONTENT_TYPE )) { - request.addHeader(entity.getContentType()); - } - // Specify a content encoding if known - if (entity.getContentEncoding() != null && !request.containsHeader( - HTTP.CONTENT_ENCODING)) { - request.addHeader(entity.getContentEncoding()); - } - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/protocol/RequestDateHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/protocol/RequestDateHC4.java deleted file mode 100644 index 16672c9d..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/protocol/RequestDateHC4.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.protocol; - -import java.io.IOException; - -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.annotation.ThreadSafe; -import org.apache.http.util.Args; - -/** - * RequestDateHC4 interceptor is responsible for adding Date header - * to the outgoing requests This interceptor is optional for client side - * protocol processors. - * - * @since 4.0 - */ -@ThreadSafe -public class RequestDateHC4 implements HttpRequestInterceptor { - - private static final HttpDateGenerator DATE_GENERATOR = new HttpDateGenerator(); - - public RequestDateHC4() { - super(); - } - - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - if ((request instanceof HttpEntityEnclosingRequest) && - !request.containsHeader(HTTP.DATE_HEADER)) { - final String httpdate = DATE_GENERATOR.getCurrentDate(); - request.setHeader(HTTP.DATE_HEADER, httpdate); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/protocol/RequestTargetHostHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/protocol/RequestTargetHostHC4.java deleted file mode 100644 index a76b7132..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/protocol/RequestTargetHostHC4.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.protocol; - -import java.io.IOException; -import java.net.InetAddress; - -import org.apache.http.HttpConnection; -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpInetConnection; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.HttpVersion; -import org.apache.http.ProtocolException; -import org.apache.http.ProtocolVersion; -import org.apache.http.annotation.Immutable; -import org.apache.http.util.Args; - -/** - * RequestTargetHostHC4 is responsible for adding Host header. This - * interceptor is required for client side protocol processors. - * - * @since 4.0 - */ -@Immutable -public class RequestTargetHostHC4 implements HttpRequestInterceptor { - - public RequestTargetHostHC4() { - super(); - } - - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - - final HttpCoreContext corecontext = HttpCoreContext.adapt(context); - - final ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); - final String method = request.getRequestLine().getMethod(); - if (method.equalsIgnoreCase("CONNECT") && ver.lessEquals(HttpVersion.HTTP_1_0)) { - return; - } - - if (!request.containsHeader(HTTP.TARGET_HOST)) { - HttpHost targethost = corecontext.getTargetHost(); - if (targethost == null) { - final HttpConnection conn = corecontext.getConnection(); - if (conn instanceof HttpInetConnection) { - // Populate the context with a default HTTP host based on the - // inet address of the target host - final InetAddress address = ((HttpInetConnection) conn).getRemoteAddress(); - final int port = ((HttpInetConnection) conn).getRemotePort(); - if (address != null) { - targethost = new HttpHost(address.getHostName(), port); - } - } - if (targethost == null) { - if (ver.lessEquals(HttpVersion.HTTP_1_0)) { - return; - } else { - throw new ProtocolException("Target host missing"); - } - } - } - request.addHeader(HTTP.TARGET_HOST, targethost.toHostString()); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/protocol/RequestUserAgentHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/protocol/RequestUserAgentHC4.java deleted file mode 100644 index 4c4f2e26..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/protocol/RequestUserAgentHC4.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.protocol; - -import java.io.IOException; - -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.annotation.Immutable; -import org.apache.http.params.CoreProtocolPNames; -import org.apache.http.params.HttpParams; -import org.apache.http.util.Args; - -/** - * RequestUserAgentHC4 is responsible for adding User-Agent header. - * This interceptor is recommended for client side protocol processors. - * - * @since 4.0 - */ -@SuppressWarnings("deprecation") -@Immutable -public class RequestUserAgentHC4 implements HttpRequestInterceptor { - - private final String userAgent; - - public RequestUserAgentHC4(final String userAgent) { - super(); - this.userAgent = userAgent; - } - - public RequestUserAgentHC4() { - this(null); - } - - public void process(final HttpRequest request, final HttpContext context) - throws HttpException, IOException { - Args.notNull(request, "HTTP request"); - if (!request.containsHeader(HTTP.USER_AGENT)) { - String s = null; - final HttpParams params = request.getParams(); - if (params != null) { - s = (String) params.getParameter(CoreProtocolPNames.USER_AGENT); - } - if (s == null) { - s = this.userAgent; - } - if (s != null) { - request.addHeader(HTTP.USER_AGENT, s); - } - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/protocol/ResponseConnControlHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/protocol/ResponseConnControlHC4.java deleted file mode 100644 index 8018cd54..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/protocol/ResponseConnControlHC4.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.protocol; - -import java.io.IOException; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.HttpResponseInterceptor; -import org.apache.http.HttpStatus; -import org.apache.http.HttpVersion; -import org.apache.http.ProtocolVersion; -import org.apache.http.annotation.Immutable; -import org.apache.http.util.Args; - -/** - * ResponseConnControlHC4 is responsible for adding Connection header - * to the outgoing responses, which is essential for managing persistence of - * HTTP/1.0 connections. This interceptor is recommended for - * server side protocol processors. - * - * @since 4.0 - */ -@Immutable -public class ResponseConnControlHC4 implements HttpResponseInterceptor { - - public ResponseConnControlHC4() { - super(); - } - - public void process(final HttpResponse response, final HttpContext context) - throws HttpException, IOException { - Args.notNull(response, "HTTP response"); - - final HttpCoreContext corecontext = HttpCoreContext.adapt(context); - - // Always drop connection after certain type of responses - final int status = response.getStatusLine().getStatusCode(); - if (status == HttpStatus.SC_BAD_REQUEST || - status == HttpStatus.SC_REQUEST_TIMEOUT || - status == HttpStatus.SC_LENGTH_REQUIRED || - status == HttpStatus.SC_REQUEST_TOO_LONG || - status == HttpStatus.SC_REQUEST_URI_TOO_LONG || - status == HttpStatus.SC_SERVICE_UNAVAILABLE || - status == HttpStatus.SC_NOT_IMPLEMENTED) { - response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); - return; - } - final Header explicit = response.getFirstHeader(HTTP.CONN_DIRECTIVE); - if (explicit != null && HTTP.CONN_CLOSE.equalsIgnoreCase(explicit.getValue())) { - // Connection persistence explicitly disabled - return; - } - // Always drop connection for HTTP/1.0 responses and below - // if the content body cannot be correctly delimited - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final ProtocolVersion ver = response.getStatusLine().getProtocolVersion(); - if (entity.getContentLength() < 0 && - (!entity.isChunked() || ver.lessEquals(HttpVersion.HTTP_1_0))) { - response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); - return; - } - } - // Drop connection if requested by the client or request was <= 1.0 - final HttpRequest request = corecontext.getRequest(); - if (request != null) { - final Header header = request.getFirstHeader(HTTP.CONN_DIRECTIVE); - if (header != null) { - response.setHeader(HTTP.CONN_DIRECTIVE, header.getValue()); - } else if (request.getProtocolVersion().lessEquals(HttpVersion.HTTP_1_0)) { - response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); - } - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/protocol/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/protocol/package-info.java deleted file mode 100644 index d4c15433..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/protocol/package-info.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Core HTTP protocol execution framework and HTTP protocol handlers - * for synchronous, blocking communication. - */ -package org.apache.http.protocol; diff --git a/lib/httpclient-android/src/main/java/org/apache/http/util/Args.java b/lib/httpclient-android/src/main/java/org/apache/http/util/Args.java deleted file mode 100644 index eed90348..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/util/Args.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.util; - -import java.util.Collection; - -public class Args { - - public static void check(final boolean expression, final String message) { - if (!expression) { - throw new IllegalArgumentException(message); - } - } - - public static void check(final boolean expression, final String message, final Object... args) { - if (!expression) { - throw new IllegalArgumentException(String.format(message, args)); - } - } - - public static T notNull(final T argument, final String name) { - if (argument == null) { - throw new IllegalArgumentException(name + " may not be null"); - } - return argument; - } - - public static T notEmpty(final T argument, final String name) { - if (argument == null) { - throw new IllegalArgumentException(name + " may not be null"); - } - if (TextUtils.isEmpty(argument)) { - throw new IllegalArgumentException(name + " may not be empty"); - } - return argument; - } - - public static T notBlank(final T argument, final String name) { - if (argument == null) { - throw new IllegalArgumentException(name + " may not be null"); - } - if (TextUtils.isBlank(argument)) { - throw new IllegalArgumentException(name + " may not be blank"); - } - return argument; - } - - public static > T notEmpty(final T argument, final String name) { - if (argument == null) { - throw new IllegalArgumentException(name + " may not be null"); - } - if (argument.isEmpty()) { - throw new IllegalArgumentException(name + " may not be empty"); - } - return argument; - } - - public static int positive(final int n, final String name) { - if (n <= 0) { - throw new IllegalArgumentException(name + " may not be negative or zero"); - } - return n; - } - - public static long positive(final long n, final String name) { - if (n <= 0) { - throw new IllegalArgumentException(name + " may not be negative or zero"); - } - return n; - } - - public static int notNegative(final int n, final String name) { - if (n < 0) { - throw new IllegalArgumentException(name + " may not be negative"); - } - return n; - } - - public static long notNegative(final long n, final String name) { - if (n < 0) { - throw new IllegalArgumentException(name + " may not be negative"); - } - return n; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/util/Asserts.java b/lib/httpclient-android/src/main/java/org/apache/http/util/Asserts.java deleted file mode 100644 index 3a383c42..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/util/Asserts.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.util; - -public class Asserts { - - public static void check(final boolean expression, final String message) { - if (!expression) { - throw new IllegalStateException(message); - } - } - - public static void check(final boolean expression, final String message, final Object... args) { - if (!expression) { - throw new IllegalStateException(String.format(message, args)); - } - } - - public static void notNull(final Object object, final String name) { - if (object == null) { - throw new IllegalStateException(name + " is null"); - } - } - - public static void notEmpty(final CharSequence s, final String name) { - if (TextUtils.isEmpty(s)) { - throw new IllegalStateException(name + " is empty"); - } - } - - public static void notBlank(final CharSequence s, final String name) { - if (TextUtils.isBlank(s)) { - throw new IllegalStateException(name + " is blank"); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/util/CharsetUtils.java b/lib/httpclient-android/src/main/java/org/apache/http/util/CharsetUtils.java deleted file mode 100644 index 33546f80..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/util/CharsetUtils.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.util; - -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.nio.charset.UnsupportedCharsetException; - -public class CharsetUtils { - - public static Charset lookup(final String name) { - if (name == null) { - return null; - } - try { - return Charset.forName(name); - } catch (final UnsupportedCharsetException ex) { - return null; - } - } - - public static Charset get(final String name) throws UnsupportedEncodingException { - if (name == null) { - return null; - } - try { - return Charset.forName(name); - } catch (final UnsupportedCharsetException ex) { - throw new UnsupportedEncodingException(name); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/util/EntityUtilsHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/util/EntityUtilsHC4.java deleted file mode 100644 index 952d5618..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/util/EntityUtilsHC4.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.util; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.nio.charset.UnsupportedCharsetException; - -import org.apache.http.HeaderElement; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.ParseException; -import org.apache.http.entity.ContentType; -import org.apache.http.protocol.HTTP; - -/** - * Static helpers for dealing with {@link HttpEntity}s. - * - * @since 4.0 - */ -public final class EntityUtilsHC4 { - - private EntityUtilsHC4() { - } - - /** - * Ensures that the entity content is fully consumed and the content stream, if exists, - * is closed. The process is done, quietly , without throwing any IOException. - * - * @param entity the entity to consume. - * - * - * @since 4.2 - */ - public static void consumeQuietly(final HttpEntity entity) { - try { - consume(entity); - } catch (final IOException ignore) { - } - } - - /** - * Ensures that the entity content is fully consumed and the content stream, if exists, - * is closed. - * - * @param entity the entity to consume. - * @throws IOException if an error occurs reading the input stream - * - * @since 4.1 - */ - public static void consume(final HttpEntity entity) throws IOException { - if (entity == null) { - return; - } - if (entity.isStreaming()) { - final InputStream instream = entity.getContent(); - if (instream != null) { - instream.close(); - } - } - } - - /** - * Updates an entity in a response by first consuming an existing entity, then setting the new one. - * - * @param response the response with an entity to update; must not be null. - * @param entity the entity to set in the response. - * @throws IOException if an error occurs while reading the input stream on the existing - * entity. - * @throws IllegalArgumentException if response is null. - * - * @since 4.3 - */ - public static void updateEntity( - final HttpResponse response, final HttpEntity entity) throws IOException { - Args.notNull(response, "Response"); - consume(response.getEntity()); - response.setEntity(entity); - } - - /** - * Read the contents of an entity and return it as a byte array. - * - * @param entity the entity to read from= - * @return byte array containing the entity content. May be null if - * {@link HttpEntity#getContent()} is null. - * @throws IOException if an error occurs reading the input stream - * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE - */ - public static byte[] toByteArray(final HttpEntity entity) throws IOException { - Args.notNull(entity, "Entity"); - final InputStream instream = entity.getContent(); - if (instream == null) { - return null; - } - try { - Args.check(entity.getContentLength() <= Integer.MAX_VALUE, - "HTTP entity too large to be buffered in memory"); - int i = (int)entity.getContentLength(); - if (i < 0) { - i = 4096; - } - final ByteArrayBuffer buffer = new ByteArrayBuffer(i); - final byte[] tmp = new byte[4096]; - int l; - while((l = instream.read(tmp)) != -1) { - buffer.append(tmp, 0, l); - } - return buffer.toByteArray(); - } finally { - instream.close(); - } - } - - /** - * Obtains character set of the entity, if known. - * - * @param entity must not be null - * @return the character set, or null if not found - * @throws ParseException if header elements cannot be parsed - * @throws IllegalArgumentException if entity is null - * - * @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)} - */ - @Deprecated - public static String getContentCharSet(final HttpEntity entity) throws ParseException { - Args.notNull(entity, "Entity"); - String charset = null; - if (entity.getContentType() != null) { - final HeaderElement values[] = entity.getContentType().getElements(); - if (values.length > 0) { - final NameValuePair param = values[0].getParameterByName("charset"); - if (param != null) { - charset = param.getValue(); - } - } - } - return charset; - } - - /** - * Obtains MIME type of the entity, if known. - * - * @param entity must not be null - * @return the character set, or null if not found - * @throws ParseException if header elements cannot be parsed - * @throws IllegalArgumentException if entity is null - * - * @since 4.1 - * - * @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)} - */ - @Deprecated - public static String getContentMimeType(final HttpEntity entity) throws ParseException { - Args.notNull(entity, "Entity"); - String mimeType = null; - if (entity.getContentType() != null) { - final HeaderElement values[] = entity.getContentType().getElements(); - if (values.length > 0) { - mimeType = values[0].getName(); - } - } - return mimeType; - } - - /** - * Get the entity content as a String, using the provided default character set - * if none is found in the entity. - * If defaultCharset is null, the default "ISO-8859-1" is used. - * - * @param entity must not be null - * @param defaultCharset character set to be applied if none found in the entity - * @return the entity content as a String. May be null if - * {@link HttpEntity#getContent()} is null. - * @throws ParseException if header elements cannot be parsed - * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE - * @throws IOException if an error occurs reading the input stream - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - */ - public static String toString( - final HttpEntity entity, final Charset defaultCharset) throws IOException, ParseException { - Args.notNull(entity, "Entity"); - final InputStream instream = entity.getContent(); - if (instream == null) { - return null; - } - try { - Args.check(entity.getContentLength() <= Integer.MAX_VALUE, - "HTTP entity too large to be buffered in memory"); - int i = (int)entity.getContentLength(); - if (i < 0) { - i = 4096; - } - Charset charset = null; - try { - final ContentType contentType = ContentType.get(entity); - if (contentType != null) { - charset = contentType.getCharset(); - } - } catch (final UnsupportedCharsetException ex) { - throw new UnsupportedEncodingException(ex.getMessage()); - } - if (charset == null) { - charset = defaultCharset; - } - if (charset == null) { - charset = Charset.forName(HTTP.DEFAULT_CONTENT_CHARSET); - } - final Reader reader = new InputStreamReader(instream, charset); - final CharArrayBuffer buffer = new CharArrayBuffer(i); - final char[] tmp = new char[1024]; - int l; - while((l = reader.read(tmp)) != -1) { - buffer.append(tmp, 0, l); - } - return buffer.toString(); - } finally { - instream.close(); - } - } - - /** - * Get the entity content as a String, using the provided default character set - * if none is found in the entity. - * If defaultCharset is null, the default "ISO-8859-1" is used. - * - * @param entity must not be null - * @param defaultCharset character set to be applied if none found in the entity - * @return the entity content as a String. May be null if - * {@link HttpEntity#getContent()} is null. - * @throws ParseException if header elements cannot be parsed - * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE - * @throws IOException if an error occurs reading the input stream - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - */ - public static String toString( - final HttpEntity entity, final String defaultCharset) throws IOException, ParseException { - return toString(entity, defaultCharset != null ? Charset.forName(defaultCharset) : null); - } - - /** - * Read the contents of an entity and return it as a String. - * The content is converted using the character set from the entity (if any), - * failing that, "ISO-8859-1" is used. - * - * @param entity the entity to convert to a string; must not be null - * @return String containing the content. - * @throws ParseException if header elements cannot be parsed - * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE - * @throws IOException if an error occurs reading the input stream - * @throws UnsupportedCharsetException Thrown when the named charset is not available in - * this instance of the Java virtual machine - */ - public static String toString(final HttpEntity entity) - throws IOException, ParseException { - return toString(entity, (Charset)null); - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/util/NetUtils.java b/lib/httpclient-android/src/main/java/org/apache/http/util/NetUtils.java deleted file mode 100644 index 6304b168..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/util/NetUtils.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.util; - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketAddress; - -/** - * @since 4.3 - */ -public final class NetUtils { - - public static void formatAddress( - final StringBuilder buffer, - final SocketAddress socketAddress) { - Args.notNull(buffer, "Buffer"); - Args.notNull(socketAddress, "Socket address"); - if (socketAddress instanceof InetSocketAddress) { - final InetSocketAddress socketaddr = ((InetSocketAddress) socketAddress); - final InetAddress inetaddr = socketaddr.getAddress(); - buffer.append(inetaddr != null ? inetaddr.getHostAddress() : inetaddr) - .append(':').append(socketaddr.getPort()); - } else { - buffer.append(socketAddress); - } - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/util/TextUtils.java b/lib/httpclient-android/src/main/java/org/apache/http/util/TextUtils.java deleted file mode 100644 index 3960c432..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/util/TextUtils.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.util; - -/** - * @since 4.3 - */ -public final class TextUtils { - - public static boolean isEmpty(final CharSequence s) { - if (s == null) { - return true; - } - return s.length() == 0; - } - - public static boolean isBlank(final CharSequence s) { - if (s == null) { - return true; - } - for (int i = 0; i < s.length(); i++) { - if (!Character.isWhitespace(s.charAt(i))) { - return false; - } - } - return true; - } - -} diff --git a/lib/httpclient-android/src/main/java/org/apache/http/util/VersionInfoHC4.java b/lib/httpclient-android/src/main/java/org/apache/http/util/VersionInfoHC4.java deleted file mode 100644 index a2f7e5af..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/util/VersionInfoHC4.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.util; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -/** - * Provides access to version information for HTTP components. - * Static methods are used to extract version information from property - * files that are automatically packaged with HTTP component release JARs. - *
    - * All available version information is provided in strings, where - * the string format is informal and subject to change without notice. - * Version information is provided for debugging output and interpretation - * by humans, not for automated processing in applications. - * - * @since 4.0 - */ -public class VersionInfoHC4 { - - /** A string constant for unavailable information. */ - public final static String UNAVAILABLE = "UNAVAILABLE"; - - /** The filename of the version information files. */ - public final static String VERSION_PROPERTY_FILE = "version.properties"; - - // the property names - public final static String PROPERTY_MODULE = "info.module"; - public final static String PROPERTY_RELEASE = "info.release"; - public final static String PROPERTY_TIMESTAMP = "info.timestamp"; - - - /** The package that contains the version information. */ - private final String infoPackage; - - /** The module from the version info. */ - private final String infoModule; - - /** The release from the version info. */ - private final String infoRelease; - - /** The timestamp from the version info. */ - private final String infoTimestamp; - - /** The classloader from which the version info was obtained. */ - private final String infoClassloader; - - - /** - * Instantiates version information. - * - * @param pckg the package - * @param module the module, or null - * @param release the release, or null - * @param time the build time, or null - * @param clsldr the class loader, or null - */ - protected VersionInfoHC4(final String pckg, final String module, - final String release, final String time, final String clsldr) { - Args.notNull(pckg, "Package identifier"); - infoPackage = pckg; - infoModule = (module != null) ? module : UNAVAILABLE; - infoRelease = (release != null) ? release : UNAVAILABLE; - infoTimestamp = (time != null) ? time : UNAVAILABLE; - infoClassloader = (clsldr != null) ? clsldr : UNAVAILABLE; - } - - - /** - * Obtains the package name. - * The package name identifies the module or informal unit. - * - * @return the package name, never null - */ - public final String getPackage() { - return infoPackage; - } - - /** - * Obtains the name of the versioned module or informal unit. - * This data is read from the version information for the package. - * - * @return the module name, never null - */ - public final String getModule() { - return infoModule; - } - - /** - * Obtains the release of the versioned module or informal unit. - * This data is read from the version information for the package. - * - * @return the release version, never null - */ - public final String getRelease() { - return infoRelease; - } - - /** - * Obtains the timestamp of the versioned module or informal unit. - * This data is read from the version information for the package. - * - * @return the timestamp, never null - */ - public final String getTimestamp() { - return infoTimestamp; - } - - /** - * Obtains the classloader used to read the version information. - * This is just the toString output of the classloader, - * since the version information should not keep a reference to - * the classloader itself. That could prevent garbage collection. - * - * @return the classloader description, never null - */ - public final String getClassloader() { - return infoClassloader; - } - - - /** - * Provides the version information in human-readable format. - * - * @return a string holding this version information - */ - @Override - public String toString() { - final StringBuilder sb = new StringBuilder - (20 + infoPackage.length() + infoModule.length() + - infoRelease.length() + infoTimestamp.length() + - infoClassloader.length()); - - sb.append("VersionInfo(") - .append(infoPackage).append(':').append(infoModule); - - // If version info is missing, a single "UNAVAILABLE" for the module - // is sufficient. Everything else just clutters the output. - if (!UNAVAILABLE.equals(infoRelease)) { - sb.append(':').append(infoRelease); - } - if (!UNAVAILABLE.equals(infoTimestamp)) { - sb.append(':').append(infoTimestamp); - } - - sb.append(')'); - - if (!UNAVAILABLE.equals(infoClassloader)) { - sb.append('@').append(infoClassloader); - } - - return sb.toString(); - } - - - /** - * Loads version information for a list of packages. - * - * @param pckgs the packages for which to load version info - * @param clsldr the classloader to load from, or - * null for the thread context classloader - * - * @return the version information for all packages found, - * never null - */ - public static VersionInfo[] loadVersionInfo(final String[] pckgs, - final ClassLoader clsldr) { - Args.notNull(pckgs, "Package identifier array"); - final List vil = new ArrayList(pckgs.length); - for (final String pckg : pckgs) { - final VersionInfoHC4 vi = loadVersionInfo(pckg, clsldr); - if (vi != null) { - vil.add(vi); - } - } - - return vil.toArray(new VersionInfo[vil.size()]); - } - - - /** - * Loads version information for a package. - * - * @param pckg the package for which to load version information, - * for example "org.apache.http". - * The package name should NOT end with a dot. - * @param clsldr the classloader to load from, or - * null for the thread context classloader - * - * @return the version information for the argument package, or - * null if not available - */ - public static VersionInfoHC4 loadVersionInfo(final String pckg, - final ClassLoader clsldr) { - Args.notNull(pckg, "Package identifier"); - final ClassLoader cl = clsldr != null ? clsldr : Thread.currentThread().getContextClassLoader(); - - Properties vip = null; // version info properties, if available - try { - // org.apache.http becomes - // org/apache/http/version.properties - final InputStream is = cl.getResourceAsStream - (pckg.replace('.', '/') + "/" + VERSION_PROPERTY_FILE); - if (is != null) { - try { - final Properties props = new Properties(); - props.load(is); - vip = props; - } finally { - is.close(); - } - } - } catch (final IOException ex) { - // shamelessly munch this exception - } - - VersionInfoHC4 result = null; - if (vip != null) { - result = fromMap(pckg, vip, cl); - } - - return result; - } - - - /** - * Instantiates version information from properties. - * - * @param pckg the package for the version information - * @param info the map from string keys to string values, - * for example {@link java.util.Properties} - * @param clsldr the classloader, or null - * - * @return the version information - */ - protected static VersionInfoHC4 fromMap(final String pckg, final Map info, - final ClassLoader clsldr) { - Args.notNull(pckg, "Package identifier"); - String module = null; - String release = null; - String timestamp = null; - - if (info != null) { - module = (String) info.get(PROPERTY_MODULE); - if ((module != null) && (module.length() < 1)) { - module = null; - } - - release = (String) info.get(PROPERTY_RELEASE); - if ((release != null) && ((release.length() < 1) || - (release.equals("${pom.version}")))) { - release = null; - } - - timestamp = (String) info.get(PROPERTY_TIMESTAMP); - if ((timestamp != null) && - ((timestamp.length() < 1) || - (timestamp.equals("${mvn.timestamp}"))) - ) { - timestamp = null; - } - } // if info - - String clsldrstr = null; - if (clsldr != null) { - clsldrstr = clsldr.toString(); - } - - return new VersionInfoHC4(pckg, module, release, timestamp, clsldrstr); - } - - /** - * Sets the user agent to {@code "/ (Java 1.5 minimum; Java/)"}. - *

    - * For example: - *

    "Apache-HttpClient/4.3 (Java 1.5 minimum; Java/1.6.0_35)"
    - * - * @param name the component name, like "Apache-HttpClient". - * @param pkg - * the package for which to load version information, for example "org.apache.http". The package name - * should NOT end with a dot. - * @param cls - * the class' class loader to load from, or null for the thread context class loader - * @since 4.3 - */ - public static String getUserAgent(final String name, final String pkg, final Class cls) { - // determine the release version from packaged version info - final VersionInfoHC4 vi = VersionInfoHC4.loadVersionInfo(pkg, cls.getClassLoader()); - final String release = (vi != null) ? vi.getRelease() : VersionInfoHC4.UNAVAILABLE; - final String javaVersion = System.getProperty("java.version"); - return name + "/" + release + " (Java 1.5 minimum; Java/" + javaVersion + ")"; - } - -} // class VersionInfoHC4 diff --git a/lib/httpclient-android/src/main/java/org/apache/http/util/package-info.java b/lib/httpclient-android/src/main/java/org/apache/http/util/package-info.java deleted file mode 100644 index 0f452443..00000000 --- a/lib/httpclient-android/src/main/java/org/apache/http/util/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -/** - * Core utility classes. - */ -package org.apache.http.util; diff --git a/settings.gradle b/settings.gradle index 8ee2b894..5c630202 100644 --- a/settings.gradle +++ b/settings.gradle @@ -7,4 +7,4 @@ */ include ':app' -include ':lib:httpclient-android' +include ':dav4android'