Implemented the HTTP state management using new protocol interceptor framework. Cookie2 support has not been ported yet

git-svn-id: https://svn.apache.org/repos/asf/jakarta/httpcomponents/httpclient/trunk@535132 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Oleg Kalnichevski 2007-05-04 09:01:16 +00:00
parent 55c1c75b10
commit 0a8b3be76d
23 changed files with 482 additions and 165 deletions

View File

@ -37,9 +37,6 @@
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.PlainSocketFactory;
import org.apache.http.conn.Scheme;
import org.apache.http.conn.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
@ -57,12 +54,6 @@ public class MethodAbort {
public final static void main(String[] args) throws Exception {
// Create a registry of available protocol schemes
SchemeRegistry supportedSchemes = new SchemeRegistry();
supportedSchemes.register(
new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
// Initialize default parameters
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

View File

@ -38,7 +38,7 @@
*
* @since 4.0
*/
public final class HTTPAuth {
public final class AUTH {
/**
* The www authenticate challange header.
@ -60,7 +60,7 @@ public final class HTTPAuth {
*/
public static final String PROXY_AUTH_RESP = "Proxy-Authorization";
private HTTPAuth() {
private AUTH() {
}
}

View File

@ -54,11 +54,6 @@ public final class CookiePolicy {
*/
public static final String RFC_2965 = "rfc2965";
/**
* The policy that ignores cookies.
*/
public static final String IGNORE_COOKIES = "ignoreCookies";
private CookiePolicy() {
super();
}

View File

@ -40,6 +40,8 @@ public class HttpClientContext extends HttpExecutionContext {
public static final String COOKIESPEC_REGISTRY = "http.cookiespec-registry";
public static final String AUTHSCHEME_REGISTRY = "http.authscheme-registry";
public static final String HTTP_STATE = "http.state";
public static final String COOKIE_SPEC = "http.cookie-spec";
public static final String COOKIE_ORIGIN = "http.cookie-origin";
public HttpClientContext(final HttpContext parentContext) {
super(parentContext);

View File

@ -0,0 +1,165 @@
/*
* $HeadURL$
* $Revision$
* $Date$
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists 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://www.apache.org/>.
*
*/
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.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.ProtocolException;
import org.apache.http.client.HttpState;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ManagedClientConnection;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.CookieSpecRegistry;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpExecutionContext;
/**
* Request interceptor that matches cookies available in the current
* {@link HttpState} to the request being executed and generates
* corresponding cookierequest headers.
*
* @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
*
* @version $Revision$
*
* @since 4.0
*/
public class RequestAddCookies implements HttpRequestInterceptor {
private static final Log LOG = LogFactory.getLog(RequestAddCookies.class);
public RequestAddCookies() {
super();
}
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
// Obtain HTTP state
HttpState state = (HttpState) context.getAttribute(
HttpClientContext.HTTP_STATE);
if (state == null) {
LOG.info("HTTP state not available in HTTP context");
return;
}
// Obtain the registry of cookie specs
CookieSpecRegistry registry= (CookieSpecRegistry) context.getAttribute(
HttpClientContext.COOKIESPEC_REGISTRY);
if (registry == null) {
LOG.info("CookieSpec registry not available in HTTP context");
return;
}
// Obtain the target host (required)
HttpHost targetHost = (HttpHost) context.getAttribute(
HttpExecutionContext.HTTP_TARGET_HOST);
if (targetHost == null) {
throw new IllegalStateException("Target host not specified in HTTP context");
}
// Obtain the client connection (required)
ManagedClientConnection conn = (ManagedClientConnection) context.getAttribute(
HttpExecutionContext.HTTP_CONNECTION);
if (conn == null) {
throw new IllegalStateException("Client connection not specified in HTTP context");
}
String policy = HttpClientParams.getCookiePolicy(request.getParams());
if (LOG.isDebugEnabled()) {
LOG.debug("CookieSpec selected: " + policy);
}
URI requestURI;
try {
requestURI = new URI(request.getRequestLine().getUri());
} catch (URISyntaxException ex) {
throw new ProtocolException("Invalid request URI: " +
request.getRequestLine().getUri(), ex);
}
CookieOrigin cookieOrigin = new CookieOrigin(
targetHost.getHostName(),
targetHost.getPort(),
requestURI.getPath(),
conn.isSecure());
// Get an instance of the selected cookie policy
CookieSpec cookieSpec = registry.getCookieSpec(policy, request.getParams());
// Get all cookies available in the HTTP state
Cookie[] cookies = state.getCookies();
// Find cookies matching the given origin
List matchedCookies = new ArrayList(cookies.length);
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieSpec.match(cookie, cookieOrigin)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Cookie " + cookie + " match " + cookieOrigin);
}
matchedCookies.add(cookie);
}
}
// Generate Cookie request headers
cookies = (Cookie[]) matchedCookies.toArray(new Cookie[matchedCookies.size()]);
if (cookies.length > 0) {
Header[] headers = cookieSpec.formatCookies(cookies);
for (int i = 0; i < headers.length; i++) {
request.addHeader(headers[i]);
}
}
// 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);
}
}

View File

@ -0,0 +1,137 @@
/*
* $HeadURL$
* $Revision$
* $Date$
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists 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://www.apache.org/>.
*
*/
package org.apache.http.client.protocol;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.HttpState;
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;
/**
* Response interceptor that populates the current {@link HttpState} with data
* contained in response cookies received in the given the HTTP response.
*
* @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
*
* @version $Revision$
*
* @since 4.0
*/
public class ResponseProcessCookies implements HttpResponseInterceptor {
private static final Log LOG = LogFactory.getLog(ResponseProcessCookies.class);
public ResponseProcessCookies() {
super();
}
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
// Obtain HTTP state
HttpState state = (HttpState) context.getAttribute(
HttpClientContext.HTTP_STATE);
if (state == null) {
LOG.info("HTTP state not available in HTTP context");
return;
}
// Obtain actual CookieSpec instance
CookieSpec cookieSpec = (CookieSpec) context.getAttribute(
HttpClientContext.COOKIE_SPEC);
if (cookieSpec == null) {
LOG.info("CookieSpec not available in HTTP context");
return;
}
// Obtain actual CookieOrigin instance
CookieOrigin cookieOrigin = (CookieOrigin) context.getAttribute(
HttpClientContext.COOKIE_ORIGIN);
if (cookieOrigin == null) {
LOG.info("CookieOrigin not available in HTTP context");
return;
}
Header[] headers = response.getHeaders(SM.SET_COOKIE);
processCookies(headers, cookieSpec, cookieOrigin, state);
}
private static void processCookies(
final Header[] headers,
final CookieSpec cookieSpec,
final CookieOrigin cookieOrigin,
final HttpState state) {
for (int i = 0; i < headers.length; i++) {
Header header = headers[i];
try {
Cookie[] cookies = cookieSpec.parse(header, cookieOrigin);
for (int c = 0; c < cookies.length; c++) {
Cookie cookie = cookies[c];
try {
cookieSpec.validate(cookie, cookieOrigin);
state.addCookie(cookie);
if (LOG.isDebugEnabled()) {
LOG.debug("Cookie accepted: \""
+ cookie + "\". ");
}
} catch (MalformedCookieException ex) {
if (LOG.isWarnEnabled()) {
LOG.warn("Cookie rejected: \""
+ cookie + "\". " + ex.getMessage());
}
}
}
} catch (MalformedCookieException ex) {
if (LOG.isWarnEnabled()) {
LOG.warn("Invalid cookie header: \""
+ header + "\". " + ex.getMessage());
}
}
}
}
}

View File

@ -33,6 +33,8 @@
import java.util.Date;
import org.apache.http.util.CharArrayBuffer;
/**
* <p>
* HTTP "magic-cookie" represents a piece of state information
@ -328,8 +330,33 @@ public boolean isDomainAttributeSpecified() {
return hasDomainAttribute;
}
public String toString() {
CharArrayBuffer buffer = new CharArrayBuffer(64);
buffer.append("[version: ");
buffer.append(Integer.toString(this.cookieVersion));
buffer.append("]");
buffer.append("[name: ");
buffer.append(this.name);
buffer.append("]");
buffer.append("[name: ");
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
private final String name;
private final String value;

View File

@ -30,6 +30,8 @@
*/
package org.apache.http.cookie;
import org.apache.http.util.CharArrayBuffer;
/**
* CookieOrigin class incapsulates details of an origin server that
* are relevant when parsing, validating or matching HTTP cookies.
@ -87,5 +89,19 @@ public int getPort() {
public boolean isSecure() {
return this.secure;
}
public String toString() {
CharArrayBuffer buffer = new CharArrayBuffer(32);
buffer.append("[");
if (this.secure) {
buffer.append("(secure)");
}
buffer.append(this.host);
buffer.append(":");
buffer.append(Integer.toString(this.port));
buffer.append(this.path);
buffer.append("]");
return buffer.toString();
}
}

View File

@ -36,7 +36,6 @@
import java.util.List;
import java.util.Map;
import org.apache.http.cookie.params.CookieSpecParams;
import org.apache.http.params.HttpParams;
/**
@ -116,28 +115,6 @@ public synchronized CookieSpec getCookieSpec(final String name, final HttpParams
}
}
/**
* Gets the {@link CookieSpec cookie specification} based on the given
* HTTP parameters. The cookie specification name will be obtained from
* the HTTP parameters.
*
* @param params the {@link HttpParams HTTP parameters} for the cookie
* specification.
*
* @return {@link CookieSpec cookie specification}
*
* @throws IllegalStateException if a policy with the given name cannot be found
*
* @see CookieSpecParams#getCookiePolicy(HttpParams)
*/
public CookieSpec getCookieSpec(final HttpParams params)
throws IllegalStateException {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return getCookieSpec(CookieSpecParams.getCookiePolicy(params), params);
}
/**
* Gets the {@link CookieSpec cookie specification} with the given name.
*

View File

@ -0,0 +1,50 @@
/*
* $HeadURL$
* $Revision$
* $Date$
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists 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://www.apache.org/>.
*
*/
package org.apache.http.cookie;
/**
* Constants and static helpers related to the HTTP state management.
*
* @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
*
* @since 4.0
*/
public final class SM {
public static final String COOKIE= "Cookie";
public static final String SET_COOKIE = "Set-Cookie";
private SM() {
}
}

View File

@ -64,57 +64,4 @@ public final class CookieSpecParams {
*/
public static final String SINGLE_COOKIE_HEADER = "http.protocol.single-cookie-header";
/**
* Defines {@link org.apache.http.cookie.CookieSpec cookie specification} to be used for cookie management.
* <p>
* This parameter expects a value of type {@link String}.
* </p>
*/
public static final String COOKIE_POLICY = "http.protocol.cookie-policy";
/**
* The policy that provides high degree of compatibilty
* 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 2109 compliant policy.
*/
public static final String RFC_2109 = "rfc2109";
/**
* The default cookie policy.
*/
public static final String DEFAULT = "default";
public static String getCookiePolicy(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
Object param = params.getParameter(COOKIE_POLICY);
if (param == null) {
return DEFAULT;
}
return (String) param;
}
/**
* Assigns the {@link org.apache.http.cookie.CookieSpecRegistry cookie policy} to be used
* when executing a request based on these parameters.
*
* @param policy the cookie policy
*/
public static void setCookiePolicy(final HttpParams params, String policy) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setParameter(COOKIE_POLICY, policy);
}
}

View File

@ -35,7 +35,7 @@
import org.apache.http.HttpRequest;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.HTTPAuth;
import org.apache.http.auth.AUTH;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.auth.params.AuthParams;
import org.apache.http.message.BufferedHeader;
@ -181,9 +181,9 @@ public static Header authenticate(
buffer.clear();
if (proxy) {
buffer.append(HTTPAuth.PROXY_AUTH_RESP);
buffer.append(AUTH.PROXY_AUTH_RESP);
} else {
buffer.append(HTTPAuth.WWW_AUTH_RESP);
buffer.append(AUTH.WWW_AUTH_RESP);
}
buffer.append(": Basic ");
buffer.append(base64password, 0, base64password.length);

View File

@ -39,7 +39,7 @@
import org.apache.http.HttpRequest;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.HTTPAuth;
import org.apache.http.auth.AUTH;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.auth.params.AuthParams;
import org.apache.http.message.BasicNameValuePair;
@ -368,9 +368,9 @@ private Header createDigestHeader(
CharArrayBuffer buffer = new CharArrayBuffer(128);
if (isProxy()) {
buffer.append(HTTPAuth.PROXY_AUTH_RESP);
buffer.append(AUTH.PROXY_AUTH_RESP);
} else {
buffer.append(HTTPAuth.WWW_AUTH_RESP);
buffer.append(AUTH.WWW_AUTH_RESP);
}
buffer.append(": Digest ");

View File

@ -36,7 +36,7 @@
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.HTTPAuth;
import org.apache.http.auth.AUTH;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.message.BasicHeaderElement;
import org.apache.http.message.BufferedHeader;
@ -90,9 +90,9 @@ public void processChallenge(final Header header) throws MalformedChallengeExcep
throw new IllegalArgumentException("Header may not be null");
}
String authheader = header.getName();
if (authheader.equalsIgnoreCase(HTTPAuth.WWW_AUTH)) {
if (authheader.equalsIgnoreCase(AUTH.WWW_AUTH)) {
this.proxy = false;
} else if (authheader.equalsIgnoreCase(HTTPAuth.PROXY_AUTH)) {
} else if (authheader.equalsIgnoreCase(AUTH.PROXY_AUTH)) {
this.proxy = true;
} else {
throw new MalformedChallengeException("Unexpected header name: " + authheader);

View File

@ -324,8 +324,13 @@ public final HttpResponse execute(HttpHost target, HttpRequest request,
// A null target may be acceptable if there is a default target.
// Otherwise, the null target is detected in determineRoute().
if (context == null)
context = new HttpExecutionContext(getContext());
synchronized (this) {
if (context == null) {
context = new HttpExecutionContext(getContext());
// Populate the context for this request
populateContext(context);
}
}
RoutedRequest roureq = determineRoute(target, request, context);
return execute(roureq, context);
@ -348,16 +353,16 @@ public final HttpResponse execute(RoutedRequest roureq, HttpContext context)
("Route must not be null.");
}
if (context == null)
context = new HttpExecutionContext(getContext());
ClientRequestDirector director = null;
// Initialize the request execution context making copies of
// all shared objects that are potentially threading unsafe.
synchronized (this) {
// Populate the context for this request
populateContext(context);
if (context == null) {
context = new HttpExecutionContext(getContext());
// Populate the context for this request
populateContext(context);
}
// Create a copy of the HTTP processor
BasicHttpProcessor httpproc = getHttpProcessor().copy();
// Create an HTTP request executor for this request

View File

@ -43,6 +43,8 @@
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.protocol.RequestAddCookies;
import org.apache.http.client.protocol.ResponseProcessCookies;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ClientConnectionManagerFactory;
import org.apache.http.conn.HttpRoute;
@ -199,6 +201,9 @@ protected BasicHttpProcessor createHttpProcessor() {
httpproc.addInterceptor(new RequestConnControl());
httpproc.addInterceptor(new RequestUserAgent());
httpproc.addInterceptor(new RequestExpectContinue());
// HTTP state management interceptors
httpproc.addInterceptor(new RequestAddCookies());
httpproc.addInterceptor(new ResponseProcessCookies());
return httpproc;
}

View File

@ -36,6 +36,7 @@
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.BufferedHeader;
import org.apache.http.util.CharArrayBuffer;
@ -135,7 +136,8 @@ public Header[] formatCookies(final Cookie[] cookies) {
throw new IllegalArgumentException("Cookie array may not be empty");
}
CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.length);
buffer.append("Cookie: ");
buffer.append(SM.COOKIE);
buffer.append(": ");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (i > 0) {

View File

@ -36,6 +36,7 @@
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.BufferedHeader;
import org.apache.http.util.CharArrayBuffer;
@ -115,7 +116,8 @@ public Header[] formatCookies(final Cookie[] cookies) {
throw new IllegalArgumentException("Cookie array may not be empty");
}
CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.length);
buffer.append("Cookie: ");
buffer.append(SM.COOKIE);
buffer.append(": ");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (i > 0) {

View File

@ -39,6 +39,7 @@
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.CookiePathComparator;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.cookie.SM;
import org.apache.http.message.BufferedHeader;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.DateUtils;
@ -148,7 +149,8 @@ private Header[] doFormatOneHeader(final Cookie[] cookies) {
}
}
CharArrayBuffer buffer = new CharArrayBuffer(40 * cookies.length);
buffer.append("Cookie: ");
buffer.append(SM.COOKIE);
buffer.append(": ");
formatParamAsVer(buffer, "$Version", Integer.toString(version), version);
for (int i = 0; i < cookies.length; i++) {
buffer.append("; ");

View File

@ -36,8 +36,6 @@
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.http.cookie.params.CookieSpecParams;
import org.apache.http.impl.cookie.BrowserCompatSpec;
import org.apache.http.impl.cookie.BrowserCompatSpecFactory;
import org.apache.http.impl.cookie.NetscapeDraftSpecFactory;
import org.apache.http.impl.cookie.RFC2109SpecFactory;
@ -62,34 +60,39 @@ public static Test suite() {
return new TestSuite(TestCookiePolicy.class);
}
private static final String BROWSER_COMPATIBILITY = "BROWSER_COMPATIBILITY";
private static final String NETSCAPE = "NETSCAPE";
private static final String RFC_2109 = "RFC_2109";
public void testRegisterUnregisterCookieSpecFactory() {
CookieSpecRegistry registry = new CookieSpecRegistry();
List names = registry.getSpecNames();
assertNotNull(names);
assertEquals(0, names.size());
registry.register(CookieSpecParams.BROWSER_COMPATIBILITY,
registry.register(BROWSER_COMPATIBILITY,
new BrowserCompatSpecFactory());
registry.register(CookieSpecParams.NETSCAPE,
registry.register(NETSCAPE,
new NetscapeDraftSpecFactory());
registry.register(CookieSpecParams.RFC_2109,
registry.register(RFC_2109,
new RFC2109SpecFactory());
registry.register(CookieSpecParams.RFC_2109,
registry.register(RFC_2109,
new RFC2109SpecFactory());
registry.register(CookieSpecParams.NETSCAPE,
registry.register(NETSCAPE,
new NetscapeDraftSpecFactory());
names = registry.getSpecNames();
assertNotNull(names);
assertEquals(3, names.size());
assertEquals(CookieSpecParams.BROWSER_COMPATIBILITY, (String) names.get(0));
assertEquals(CookieSpecParams.NETSCAPE, (String) names.get(1));
assertEquals(CookieSpecParams.RFC_2109, (String) names.get(2));
assertEquals(BROWSER_COMPATIBILITY, (String) names.get(0));
assertEquals(NETSCAPE, (String) names.get(1));
assertEquals(RFC_2109, (String) names.get(2));
registry.unregister(CookieSpecParams.NETSCAPE);
registry.unregister(CookieSpecParams.NETSCAPE);
registry.unregister(CookieSpecParams.RFC_2109);
registry.unregister(CookieSpecParams.BROWSER_COMPATIBILITY);
registry.unregister(NETSCAPE);
registry.unregister(NETSCAPE);
registry.unregister(RFC_2109);
registry.unregister(BROWSER_COMPATIBILITY);
registry.unregister("whatever");
names = registry.getSpecNames();
@ -99,16 +102,16 @@ public void testRegisterUnregisterCookieSpecFactory() {
public void testGetNewCookieSpec() {
CookieSpecRegistry registry = new CookieSpecRegistry();
registry.register(CookieSpecParams.BROWSER_COMPATIBILITY,
registry.register(BROWSER_COMPATIBILITY,
new BrowserCompatSpecFactory());
registry.register(CookieSpecParams.NETSCAPE,
registry.register(NETSCAPE,
new NetscapeDraftSpecFactory());
registry.register(CookieSpecParams.RFC_2109,
registry.register(RFC_2109,
new RFC2109SpecFactory());
assertNotNull(registry.getCookieSpec(CookieSpecParams.NETSCAPE));
assertNotNull(registry.getCookieSpec(CookieSpecParams.RFC_2109));
assertNotNull(registry.getCookieSpec(CookieSpecParams.BROWSER_COMPATIBILITY));
assertNotNull(registry.getCookieSpec(NETSCAPE));
assertNotNull(registry.getCookieSpec(RFC_2109));
assertNotNull(registry.getCookieSpec(BROWSER_COMPATIBILITY));
try {
registry.getCookieSpec("whatever");
fail("IllegalStateException should have been thrown");
@ -116,18 +119,15 @@ public void testGetNewCookieSpec() {
// expected
}
HttpParams params = new BasicHttpParams();
assertNotNull(registry.getCookieSpec(CookieSpecParams.NETSCAPE, params));
assertNotNull(registry.getCookieSpec(CookieSpecParams.RFC_2109, params));
assertNotNull(registry.getCookieSpec(CookieSpecParams.BROWSER_COMPATIBILITY, params));
assertNotNull(registry.getCookieSpec(NETSCAPE, params));
assertNotNull(registry.getCookieSpec(RFC_2109, params));
assertNotNull(registry.getCookieSpec(BROWSER_COMPATIBILITY, params));
try {
registry.getCookieSpec("whatever", params);
fail("IllegalStateException should have been thrown");
} catch (IllegalStateException ex) {
// expected
}
CookieSpecParams.setCookiePolicy(params, CookieSpecParams.BROWSER_COMPATIBILITY);
CookieSpec cookiespec = registry.getCookieSpec(params);
assertTrue(cookiespec instanceof BrowserCompatSpec);
}
public void testInvalidInput() {
@ -156,12 +156,6 @@ public void testInvalidInput() {
} catch (IllegalArgumentException ex) {
// expected
}
try {
registry.getCookieSpec((HttpParams)null);
fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
}
}

View File

@ -39,7 +39,7 @@
import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.HTTPAuth;
import org.apache.http.auth.AUTH;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.message.BasicHeader;
@ -75,7 +75,7 @@ public static Test suite() {
public void testBasicAuthenticationWithNoRealm() {
String challenge = "Basic";
Header header = new BasicHeader(HTTPAuth.WWW_AUTH, challenge);
Header header = new BasicHeader(AUTH.WWW_AUTH, challenge);
try {
AuthScheme authscheme = new BasicScheme();
authscheme.processChallenge(header);
@ -101,7 +101,7 @@ public void testBasicAuthentication() throws Exception {
UsernamePasswordCredentials creds =
new UsernamePasswordCredentials("testuser", "testpass");
Header challenge = new BasicHeader(HTTPAuth.WWW_AUTH, "Basic realm=\"test\"");
Header challenge = new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\"");
BasicScheme authscheme = new BasicScheme();
authscheme.processChallenge(challenge);
@ -111,7 +111,7 @@ public void testBasicAuthentication() throws Exception {
String expected = "Basic " + EncodingUtils.getAsciiString(
Base64.encodeBase64(EncodingUtils.getAsciiBytes("testuser:testpass")));
assertEquals(HTTPAuth.WWW_AUTH_RESP, authResponse.getName());
assertEquals(AUTH.WWW_AUTH_RESP, authResponse.getName());
assertEquals(expected, authResponse.getValue());
assertEquals("test", authscheme.getRealm());
assertTrue(authscheme.isComplete());
@ -122,7 +122,7 @@ public void testBasicProxyAuthentication() throws Exception {
UsernamePasswordCredentials creds =
new UsernamePasswordCredentials("testuser", "testpass");
Header challenge = new BasicHeader(HTTPAuth.PROXY_AUTH, "Basic realm=\"test\"");
Header challenge = new BasicHeader(AUTH.PROXY_AUTH, "Basic realm=\"test\"");
BasicScheme authscheme = new BasicScheme();
authscheme.processChallenge(challenge);
@ -132,7 +132,7 @@ public void testBasicProxyAuthentication() throws Exception {
String expected = "Basic " + EncodingUtils.getAsciiString(
Base64.encodeBase64(EncodingUtils.getAsciiBytes("testuser:testpass")));
assertEquals(HTTPAuth.PROXY_AUTH_RESP, authResponse.getName());
assertEquals(AUTH.PROXY_AUTH_RESP, authResponse.getName());
assertEquals(expected, authResponse.getValue());
assertEquals("test", authscheme.getRealm());
assertTrue(authscheme.isComplete());

View File

@ -41,7 +41,7 @@
import org.apache.http.HttpRequest;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.HTTPAuth;
import org.apache.http.auth.AUTH;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.message.BasicHeader;
@ -75,7 +75,7 @@ public static Test suite() {
}
public void testDigestAuthenticationWithNoRealm() throws Exception {
Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, "Digest");
Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, "Digest");
try {
AuthScheme authscheme = new DigestScheme();
authscheme.processChallenge(authChallenge);
@ -86,7 +86,7 @@ public void testDigestAuthenticationWithNoRealm() throws Exception {
}
public void testDigestAuthenticationWithNoRealm2() throws Exception {
Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, "Digest ");
Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, "Digest ");
try {
AuthScheme authscheme = new DigestScheme();
authscheme.processChallenge(authChallenge);
@ -98,7 +98,7 @@ public void testDigestAuthenticationWithNoRealm2() throws Exception {
public void testDigestAuthenticationWithDefaultCreds() throws Exception {
String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge);
Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
HttpRequest request = new BasicHttpRequest("Simple", "/");
Credentials cred = new UsernamePasswordCredentials("username","password");
AuthScheme authscheme = new DigestScheme();
@ -115,7 +115,7 @@ public void testDigestAuthenticationWithDefaultCreds() throws Exception {
public void testDigestAuthentication() throws Exception {
String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge);
Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
HttpRequest request = new BasicHttpRequest("Simple", "/");
Credentials cred = new UsernamePasswordCredentials("username","password");
AuthScheme authscheme = new DigestScheme();
@ -132,7 +132,7 @@ public void testDigestAuthentication() throws Exception {
public void testDigestAuthenticationWithQueryStringInDigestURI() throws Exception {
String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge);
Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
HttpRequest request = new BasicHttpRequest("Simple", "/?param=value");
Credentials cred = new UsernamePasswordCredentials("username","password");
AuthScheme authscheme = new DigestScheme();
@ -153,7 +153,7 @@ public void testDigestAuthenticationWithMultipleRealms() throws Exception {
Credentials cred = new UsernamePasswordCredentials("username","password");
Credentials cred2 = new UsernamePasswordCredentials("uname2","password2");
Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge1);
Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge1);
HttpRequest request = new BasicHttpRequest("Simple", "/");
AuthScheme authscheme = new DigestScheme();
authscheme.processChallenge(authChallenge);
@ -166,7 +166,7 @@ public void testDigestAuthenticationWithMultipleRealms() throws Exception {
assertEquals("abcde", table.get("nonce"));
assertEquals("786f500303eac1478f3c2865e676ed68", table.get("response"));
authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge2);
authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge2);
AuthScheme authscheme2 = new DigestScheme();
authscheme2.processChallenge(authChallenge);
authResponse = authscheme2.authenticate(cred2, request);
@ -197,7 +197,7 @@ public void testDigestAuthenticationMD5Sess() throws Exception {
+ "algorithm=MD5-sess, "
+ "qop=\"auth,auth-int\""; // we pass both but expect auth to be used
Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge);
Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
Credentials cred = new UsernamePasswordCredentials(username, password);
HttpRequest request = new BasicHttpRequest("Simple", "/");
@ -241,7 +241,7 @@ public void testDigestAuthenticationMD5SessNoQop() throws Exception {
+ "stale=false, "
+ "algorithm=MD5-sess";
Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge);
Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
Credentials cred = new UsernamePasswordCredentials(username, password);
@ -280,7 +280,7 @@ public void testDigestAuthenticationMD5SessInvalidQop() throws Exception {
+ "algorithm=MD5-sess, "
+ "qop=\"jakarta\""; // jakarta is an invalid qop value
Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge);
Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
try {
AuthScheme authscheme = new DigestScheme();
@ -293,7 +293,7 @@ public void testDigestAuthenticationMD5SessInvalidQop() throws Exception {
public void testDigestAuthenticationWithStaleNonce() throws Exception {
String challenge = "Digest realm=\"realm1\", " +
"nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", stale=\"true\"";
Header authChallenge = new BasicHeader(HTTPAuth.WWW_AUTH, challenge);
Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
AuthScheme authscheme = new DigestScheme();
authscheme.processChallenge(authChallenge);

View File

@ -34,7 +34,7 @@
import org.apache.http.HttpRequest;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.HTTPAuth;
import org.apache.http.auth.AUTH;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BufferedHeader;
@ -84,7 +84,7 @@ public boolean isConnectionBased() {
public void testProcessChallenge() throws Exception {
TestAuthScheme authscheme = new TestAuthScheme();
Header header = new BasicHeader(
HTTPAuth.WWW_AUTH,
AUTH.WWW_AUTH,
"Test realm=\"realm1\", test, test1 = stuff, test2 = \"stuff, stuff\", test3=\"crap");
authscheme.processChallenge(header);
@ -122,7 +122,7 @@ public void testInvalidHeader() throws Exception {
public void testEmptyHeader() throws Exception {
TestAuthScheme authscheme = new TestAuthScheme();
Header header = new BasicHeader(HTTPAuth.WWW_AUTH, "Test ");
Header header = new BasicHeader(AUTH.WWW_AUTH, "Test ");
try {
authscheme.processChallenge(header);
fail("MalformedChallengeException should have been thrown");