Removed obsolete cookie elements and obsolete cookie policies

git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@1681484 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Oleg Kalnichevski 2015-05-24 16:36:03 +00:00
parent 3b5990e363
commit 64ce856b92
52 changed files with 114 additions and 5834 deletions

View File

@ -37,11 +37,6 @@ import org.apache.http.annotation.Immutable;
@Immutable
public final class CookieSpecs {
/**
* The Netscape cookie draft compliant policy.
*/
public static final String NETSCAPE = "netscape";
/**
* The RFC 6265 compliant policy (interoprability profile).
*/

View File

@ -189,15 +189,6 @@ public class RequestAddCookies implements HttpRequestInterceptor {
}
}
final int ver = cookieSpec.getVersion();
if (ver > 0) {
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);

View File

@ -88,16 +88,8 @@ public class ResponseProcessCookies implements HttpResponseInterceptor {
this.log.debug("Cookie origin not specified in HTTP context");
return;
}
HeaderIterator it = response.headerIterator(SM.SET_COOKIE);
final 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(
@ -145,8 +137,6 @@ public class ResponseProcessCookies implements HttpResponseInterceptor {
buf.append(v);
}
buf.append("\"");
buf.append(", version:");
buf.append(Integer.toString(cookie.getVersion()));
buf.append(", domain:");
buf.append(cookie.getDomain());
buf.append(", path:");

View File

@ -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
* <http://www.apache.org/>.
*
*/
package org.apache.http.cookie;
import org.apache.http.annotation.Obsolete;
/**
* ClientCookie extends the standard {@link Cookie} interface with
* additional client specific functionality such ability to retrieve
* original cookie attributes exactly as they were specified by the
* origin server. This is important for generating the {@code Cookie}
* header because some cookie specifications require that the
* {@code Cookie} header should include certain attributes only if
* they were specified in the {@code Set-Cookie} header.
* <p>
* Please do not use attributes marked as @Obsolete. They have been rendered
* obsolete by RFC 6265.
*
* @since 4.0
*/
public interface ClientCookie extends Cookie {
@Obsolete
public static final String VERSION_ATTR = "version";
public static final String PATH_ATTR = "path";
public static final String DOMAIN_ATTR = "domain";
public static final String MAX_AGE_ATTR = "max-age";
public static final String SECURE_ATTR = "secure";
@Obsolete
public static final String COMMENT_ATTR = "comment";
public static final String EXPIRES_ATTR = "expires";
@Obsolete
public static final String PORT_ATTR = "port";
@Obsolete
public static final String COMMENTURL_ATTR = "commenturl";
@Obsolete
public static final String DISCARD_ATTR = "discard";
String getAttribute(String name);
boolean containsAttribute(String name);
}

View File

@ -29,8 +29,6 @@ package org.apache.http.cookie;
import java.util.Date;
import org.apache.http.annotation.Obsolete;
/**
* Cookie interface represents a token or short packet of state information
* (also referred to as "magic-cookie") that the HTTP agent and the target
@ -44,6 +42,22 @@ import org.apache.http.annotation.Obsolete;
*/
public interface Cookie {
String PATH_ATTR = "path";
String DOMAIN_ATTR = "domain";
String MAX_AGE_ATTR = "max-age";
String SECURE_ATTR = "secure";
String EXPIRES_ATTR = "expires";
/**
* @since 5.0
*/
String getAttribute(String name);
/**
* @since 5.0
*/
boolean containsAttribute(String name);
/**
* Returns the name.
*
@ -58,22 +72,6 @@ public interface Cookie {
*/
String getValue();
/**
* Returns the comment describing the purpose of this cookie, or
* {@code null} if no such comment has been defined.
*
* @return comment
*/
@Obsolete
String getComment();
/**
* If a user agent (web browser) presents this cookie to a user, the
* cookie's purpose will be described by the information at this URL.
*/
@Obsolete
String getCommentURL();
/**
* Returns the expiration {@link Date} of the cookie, or {@code null}
* if none exists.
@ -110,13 +108,6 @@ public interface Cookie {
*/
String getPath();
/**
* Get the Port attribute. It restricts the ports to which a cookie
* may be returned in a Cookie request header.
*/
@Obsolete
int[] getPorts();
/**
* Indicates whether this cookie requires a secure connection.
*
@ -125,15 +116,6 @@ public interface Cookie {
*/
boolean isSecure();
/**
* Returns the version of the cookie specification to which this
* cookie conforms.
*
* @return the version of the cookie.
*/
@Obsolete
int getVersion();
/**
* Returns true if this cookie has expired.
* @param date Current time

View File

@ -30,7 +30,6 @@ package org.apache.http.cookie;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.annotation.Obsolete;
/**
* Defines the cookie management specification.
@ -49,15 +48,6 @@ import org.apache.http.annotation.Obsolete;
*/
public interface CookieSpec {
/**
* Returns version of the state management this cookie specification
* conforms to.
*
* @return version of the state management specification
*/
@Obsolete
int getVersion();
/**
* Parse the {@code "Set-Cookie"} Header into an array of Cookies.
*
@ -103,12 +93,4 @@ public interface CookieSpec {
*/
List<Header> formatCookies(List<Cookie> cookies);
/**
* Returns a request header identifying what version of the state management
* specification is understood. May be {@code null} if the cookie
* specification does not support {@code Cookie2} header.
*/
@Obsolete
Header getVersionHeader();
}

View File

@ -36,8 +36,6 @@ package org.apache.http.cookie;
public interface SM {
public static final String COOKIE = "Cookie";
public static final String COOKIE2 = "Cookie2";
public static final String SET_COOKIE = "Set-Cookie";
public static final String SET_COOKIE2 = "Set-Cookie2";
}

View File

@ -29,8 +29,6 @@ package org.apache.http.cookie;
import java.util.Date;
import org.apache.http.annotation.Obsolete;
/**
* This interface represents a {@code Set-Cookie} response header sent by the
* origin server to the HTTP agent in order to maintain a conversational state.
@ -44,17 +42,6 @@ public interface SetCookie extends Cookie {
void setValue(String value);
/**
* 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()
*/
@Obsolete
void setComment(String comment);
/**
* Sets expiration date.
* <p><strong>Note:</strong> the object returned by this method is considered
@ -101,16 +88,5 @@ public interface SetCookie extends Cookie {
*/
void setSecure (boolean secure);
/**
* Sets the version of the cookie specification to which this
* cookie conforms.
*
* @param version the version of the cookie.
*
* @see Cookie#getVersion
*/
@Obsolete
void setVersion(int version);
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
package org.apache.http.cookie;
import org.apache.http.annotation.Obsolete;
/**
* This interface represents a {@code Set-Cookie2} response header sent by the
* origin server to the HTTP agent in order to maintain a conversational state.
* <p>
* Please do not use methods marked as @Obsolete. They have been rendered
* obsolete by RFC 6265
*
* @since 4.0
*/
public interface SetCookie2 extends SetCookie {
/**
* If a user agent (web browser) presents this cookie to a user, the
* cookie's purpose will be described by the information at this URL.
*/
@Obsolete
void setCommentURL(String commentURL);
/**
* Sets the Port attribute. It restricts the ports to which a cookie
* may be returned in a Cookie request header.
*/
@Obsolete
void setPorts(int[] ports);
/**
* Set the Discard attribute.
*
* Note: {@code Discard} attribute overrides {@code Max-age}.
*
* @see #isPersistent()
*/
@Obsolete
void setDiscard(boolean discard);
}

View File

@ -33,9 +33,7 @@ import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.impl.cookie.DefaultCookieSpecProvider;
import org.apache.http.impl.cookie.IgnoreSpecProvider;
import org.apache.http.impl.cookie.NetscapeDraftSpecProvider;
import org.apache.http.impl.cookie.RFC6265CookieSpecProvider;
/**
@ -47,18 +45,14 @@ public final class CookieSpecRegistries {
* Creates a builder containing the default registry entries, using the provided public suffix matcher.
*/
public static RegistryBuilder<CookieSpecProvider> createDefaultBuilder(final PublicSuffixMatcher publicSuffixMatcher) {
final CookieSpecProvider defaultProvider = new DefaultCookieSpecProvider(publicSuffixMatcher);
final CookieSpecProvider laxStandardProvider = new RFC6265CookieSpecProvider(
RFC6265CookieSpecProvider.CompatibilityLevel.RELAXED, publicSuffixMatcher);
final CookieSpecProvider strictStandardProvider = new RFC6265CookieSpecProvider(
RFC6265CookieSpecProvider.CompatibilityLevel.STRICT, publicSuffixMatcher);
return RegistryBuilder.<CookieSpecProvider>create()
.register(CookieSpecs.DEFAULT, defaultProvider)
.register("best-match", defaultProvider)
.register("compatibility", defaultProvider)
.register(CookieSpecs.DEFAULT, laxStandardProvider)
.register(CookieSpecs.STANDARD, laxStandardProvider)
.register(CookieSpecs.STANDARD_STRICT, strictStandardProvider)
.register(CookieSpecs.NETSCAPE, new NetscapeDraftSpecProvider())
.register(CookieSpecs.IGNORE_COOKIES, new IgnoreSpecProvider());
}

View File

@ -34,7 +34,7 @@ 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.Cookie;
import org.apache.http.cookie.SetCookie;
import org.apache.http.util.Args;
@ -44,7 +44,7 @@ import org.apache.http.util.Args;
* @since 4.0
*/
@NotThreadSafe
public class BasicClientCookie implements SetCookie, ClientCookie, Cloneable, Serializable {
public class BasicClientCookie implements SetCookie, Cloneable, Serializable, Cookie {
private static final long serialVersionUID = -3869795591041535538L;
@ -92,42 +92,6 @@ public class BasicClientCookie implements SetCookie, ClientCookie, Cloneable, Se
this.value = value;
}
/**
* Returns the comment describing the purpose of this cookie, or
* {@code null} if no such comment has been defined.
*
* @return comment
*
* @see #setComment(String)
*/
@Override
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()
*/
@Override
public void setComment(final String comment) {
cookieComment = comment;
}
/**
* Returns null. Cookies prior to RFC2965 do not set this attribute
*/
@Override
public String getCommentURL() {
return null;
}
/**
* Returns the expiration {@link Date} of the cookie, or {@code null}
* if none exists.
@ -254,43 +218,6 @@ public class BasicClientCookie implements SetCookie, ClientCookie, Cloneable, Se
isSecure = secure;
}
/**
* Returns null. Cookies prior to RFC2965 do not set this attribute
*/
@Override
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)
*
*/
@Override
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
*/
@Override
public void setVersion(final int version) {
cookieVersion = version;
}
/**
* Returns true if this cookie has expired.
* @param date Current time
@ -349,22 +276,19 @@ public class BasicClientCookie implements SetCookie, ClientCookie, Cloneable, Se
@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("; ");
buffer.append("value: ");
buffer.append(this.value);
buffer.append("]");
buffer.append("[domain: ");
buffer.append("; ");
buffer.append("domain: ");
buffer.append(this.cookieDomain);
buffer.append("]");
buffer.append("[path: ");
buffer.append("; ");
buffer.append("path: ");
buffer.append(this.cookiePath);
buffer.append("]");
buffer.append("[expiry: ");
buffer.append("; ");
buffer.append("expiry: ");
buffer.append(this.cookieExpiryDate);
buffer.append("]");
return buffer.toString();
@ -381,9 +305,6 @@ public class BasicClientCookie implements SetCookie, ClientCookie, Cloneable, Se
/** Cookie value */
private String value;
/** Comment attribute. */
private String cookieComment;
/** Domain attribute. */
private String cookieDomain;
@ -396,9 +317,6 @@ public class BasicClientCookie implements SetCookie, ClientCookie, Cloneable, Se
/** My secure flag. */
private boolean isSecure;
/** The version of the cookie specification I was created from. */
private int cookieVersion;
private Date creationDate;
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
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 BasicClientCookie2 extends BasicClientCookie 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 BasicClientCookie2(final String name, final String value) {
super(name, value);
}
@Override
public int[] getPorts() {
return this.ports;
}
@Override
public void setPorts(final int[] ports) {
this.ports = ports;
}
@Override
public String getCommentURL() {
return this.commentURL;
}
@Override
public void setCommentURL(final String commentURL) {
this.commentURL = commentURL;
}
@Override
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 BasicClientCookie2 clone = (BasicClientCookie2) super.clone();
if (this.ports != null) {
clone.ports = this.ports.clone();
}
return clone;
}
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.cookie;
import org.apache.http.annotation.Immutable;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.cookie.SetCookie;
import org.apache.http.util.Args;
/**
*
* @since 4.0
*/
@Immutable
public class BasicCommentHandler extends AbstractCookieAttributeHandler implements CommonCookieAttributeHandler {
public BasicCommentHandler() {
super();
}
@Override
public void parse(final SetCookie cookie, final String value)
throws MalformedCookieException {
Args.notNull(cookie, "Cookie");
cookie.setComment(value);
}
@Override
public String getAttributeName() {
return ClientCookie.COMMENT_ATTR;
}
}

View File

@ -30,7 +30,6 @@ import java.util.Locale;
import org.apache.http.annotation.Immutable;
import org.apache.http.conn.util.InetAddressUtils;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
@ -125,17 +124,15 @@ public class BasicDomainHandler implements CommonCookieAttributeHandler {
if (host.equals(domain)) {
return true;
}
if (cookie instanceof ClientCookie) {
if (((ClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR)) {
if ((cookie.containsAttribute(Cookie.DOMAIN_ATTR))) {
return domainMatch(domain, host);
}
}
return false;
}
@Override
public String getAttributeName() {
return ClientCookie.DOMAIN_ATTR;
return Cookie.DOMAIN_ATTR;
}
}

View File

@ -30,8 +30,8 @@ import java.util.Date;
import org.apache.http.annotation.Immutable;
import org.apache.http.client.utils.DateUtils;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.cookie.SetCookie;
import org.apache.http.util.Args;
@ -68,7 +68,7 @@ public class BasicExpiresHandler extends AbstractCookieAttributeHandler implemen
@Override
public String getAttributeName() {
return ClientCookie.EXPIRES_ATTR;
return Cookie.EXPIRES_ATTR;
}
}

View File

@ -29,8 +29,8 @@ package org.apache.http.impl.cookie;
import java.util.Date;
import org.apache.http.annotation.Immutable;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.cookie.SetCookie;
import org.apache.http.util.Args;
@ -69,7 +69,7 @@ public class BasicMaxAgeHandler extends AbstractCookieAttributeHandler implement
@Override
public String getAttributeName() {
return ClientCookie.MAX_AGE_ATTR;
return Cookie.MAX_AGE_ATTR;
}
}

View File

@ -27,7 +27,6 @@
package org.apache.http.impl.cookie;
import org.apache.http.annotation.Immutable;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
@ -96,7 +95,7 @@ public class BasicPathHandler implements CommonCookieAttributeHandler {
@Override
public String getAttributeName() {
return ClientCookie.PATH_ATTR;
return Cookie.PATH_ATTR;
}
}

View File

@ -27,7 +27,6 @@
package org.apache.http.impl.cookie;
import org.apache.http.annotation.Immutable;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
@ -62,7 +61,7 @@ public class BasicSecureHandler extends AbstractCookieAttributeHandler implement
@Override
public String getAttributeName() {
return ClientCookie.SECURE_ATTR;
return Cookie.SECURE_ATTR;
}
}

View File

@ -1,220 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists 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.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.ThreadSafe;
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;
/**
* Default cookie specification that picks up the best matching cookie policy based on
* the format of cookies sent with the HTTP response.
*
* @since 4.4
*/
@ThreadSafe
public class DefaultCookieSpec implements CookieSpec {
private final RFC2965Spec strict;
private final RFC2109Spec obsoleteStrict;
private final NetscapeDraftSpec netscapeDraft;
DefaultCookieSpec(
final RFC2965Spec strict,
final RFC2109Spec obsoleteStrict,
final NetscapeDraftSpec netscapeDraft) {
this.strict = strict;
this.obsoleteStrict = obsoleteStrict;
this.netscapeDraft = netscapeDraft;
}
public DefaultCookieSpec(
final String[] datepatterns,
final boolean oneHeader) {
this.strict = new RFC2965Spec(oneHeader,
new RFC2965VersionAttributeHandler(),
new BasicPathHandler(),
new RFC2965DomainAttributeHandler(),
new RFC2965PortAttributeHandler(),
new BasicMaxAgeHandler(),
new BasicSecureHandler(),
new BasicCommentHandler(),
new RFC2965CommentUrlAttributeHandler(),
new RFC2965DiscardAttributeHandler());
this.obsoleteStrict = new RFC2109Spec(oneHeader,
new RFC2109VersionHandler(),
new BasicPathHandler(),
new RFC2109DomainHandler(),
new BasicMaxAgeHandler(),
new BasicSecureHandler(),
new BasicCommentHandler());
this.netscapeDraft = new NetscapeDraftSpec(
new BasicDomainHandler(),
new BasicPathHandler(),
new BasicSecureHandler(),
new BasicCommentHandler(),
new BasicExpiresHandler(
datepatterns != null ? datepatterns.clone() : new String[]{NetscapeDraftSpec.EXPIRES_PATTERN}));
}
public DefaultCookieSpec() {
this(null, false);
}
@Override
public List<Cookie> 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 NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.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 netscapeDraft.parse(helems, origin);
} else {
if (SM.SET_COOKIE2.equals(header.getName())) {
return strict.parse(helems, origin);
} else {
return obsoleteStrict.parse(helems, origin);
}
}
}
@Override
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) {
strict.validate(cookie, origin);
} else {
obsoleteStrict.validate(cookie, origin);
}
} else {
netscapeDraft.validate(cookie, origin);
}
}
@Override
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 strict.match(cookie, origin);
} else {
return obsoleteStrict.match(cookie, origin);
}
} else {
return netscapeDraft.match(cookie, origin);
}
}
@Override
public List<Header> formatCookies(final List<Cookie> 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 strict.formatCookies(cookies);
} else {
return obsoleteStrict.formatCookies(cookies);
}
} else {
return netscapeDraft.formatCookies(cookies);
}
}
@Override
public int getVersion() {
return strict.getVersion();
}
@Override
public Header getVersionHeader() {
return null;
}
@Override
public String toString() {
return "default";
}
}

View File

@ -1,134 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists 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.impl.cookie;
import org.apache.http.annotation.Immutable;
import org.apache.http.conn.util.PublicSuffixMatcher;
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.MalformedCookieException;
import org.apache.http.protocol.HttpContext;
/**
* {@link org.apache.http.cookie.CookieSpecProvider} implementation that provides an instance of
* {@link org.apache.http.impl.cookie.DefaultCookieSpec}. The instance returned by this factory can
* be shared by multiple threads.
*
* @since 4.4
*/
@Immutable
public class DefaultCookieSpecProvider implements CookieSpecProvider {
public enum CompatibilityLevel {
DEFAULT,
IE_MEDIUM_SECURITY
}
private final CompatibilityLevel compatibilityLevel;
private final PublicSuffixMatcher publicSuffixMatcher;
private final String[] datepatterns;
private final boolean oneHeader;
private volatile CookieSpec cookieSpec;
public DefaultCookieSpecProvider(
final CompatibilityLevel compatibilityLevel,
final PublicSuffixMatcher publicSuffixMatcher,
final String[] datepatterns,
final boolean oneHeader) {
super();
this.compatibilityLevel = compatibilityLevel != null ? compatibilityLevel : CompatibilityLevel.DEFAULT;
this.publicSuffixMatcher = publicSuffixMatcher;
this.datepatterns = datepatterns;
this.oneHeader = oneHeader;
}
public DefaultCookieSpecProvider(
final CompatibilityLevel compatibilityLevel,
final PublicSuffixMatcher publicSuffixMatcher) {
this(compatibilityLevel, publicSuffixMatcher, null, false);
}
public DefaultCookieSpecProvider(final PublicSuffixMatcher publicSuffixMatcher) {
this(CompatibilityLevel.DEFAULT, publicSuffixMatcher, null, false);
}
public DefaultCookieSpecProvider() {
this(CompatibilityLevel.DEFAULT, null, null, false);
}
@Override
public CookieSpec create(final HttpContext context) {
if (cookieSpec == null) {
synchronized (this) {
if (cookieSpec == null) {
final RFC2965Spec strict = new RFC2965Spec(this.oneHeader,
new RFC2965VersionAttributeHandler(),
new BasicPathHandler(),
PublicSuffixDomainFilter.decorate(
new RFC2965DomainAttributeHandler(), this.publicSuffixMatcher),
new RFC2965PortAttributeHandler(),
new BasicMaxAgeHandler(),
new BasicSecureHandler(),
new BasicCommentHandler(),
new RFC2965CommentUrlAttributeHandler(),
new RFC2965DiscardAttributeHandler());
final RFC2109Spec obsoleteStrict = new RFC2109Spec(this.oneHeader,
new RFC2109VersionHandler(),
new BasicPathHandler(),
PublicSuffixDomainFilter.decorate(
new RFC2109DomainHandler(), this.publicSuffixMatcher),
new BasicMaxAgeHandler(),
new BasicSecureHandler(),
new BasicCommentHandler());
final NetscapeDraftSpec netscapeDraft = new NetscapeDraftSpec(
PublicSuffixDomainFilter.decorate(
new BasicDomainHandler(), this.publicSuffixMatcher),
this.compatibilityLevel == CompatibilityLevel.IE_MEDIUM_SECURITY ?
new BasicPathHandler() {
@Override
public void validate(
final Cookie cookie,
final CookieOrigin origin) throws MalformedCookieException {
// No validation
}
} : new BasicPathHandler(),
new BasicSecureHandler(),
new BasicCommentHandler(),
new BasicExpiresHandler(this.datepatterns != null ? this.datepatterns.clone() :
new String[]{NetscapeDraftSpec.EXPIRES_PATTERN}));
this.cookieSpec = new DefaultCookieSpec(strict, obsoleteStrict, netscapeDraft);
}
}
}
return this.cookieSpec;
}
}

View File

@ -44,11 +44,6 @@ import org.apache.http.cookie.MalformedCookieException;
@ThreadSafe
public class IgnoreSpec extends CookieSpecBase {
@Override
public int getVersion() {
return 0;
}
@Override
public List<Cookie> parse(final Header header, final CookieOrigin origin)
throws MalformedCookieException {
@ -60,8 +55,4 @@ public class IgnoreSpec extends CookieSpecBase {
return Collections.emptyList();
}
@Override
public Header getVersionHeader() {
return null;
}
}

View File

@ -36,8 +36,8 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.annotation.Immutable;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.cookie.SetCookie;
import org.apache.http.message.ParserCursor;
@ -214,7 +214,7 @@ public class LaxExpiresHandler extends AbstractCookieAttributeHandler implements
@Override
public String getAttributeName() {
return ClientCookie.EXPIRES_ATTR;
return Cookie.EXPIRES_ATTR;
}
}

View File

@ -31,8 +31,8 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.annotation.Immutable;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.cookie.SetCookie;
import org.apache.http.util.Args;
@ -73,7 +73,7 @@ public class LaxMaxAgeHandler extends AbstractCookieAttributeHandler implements
@Override
public String getAttributeName() {
return ClientCookie.MAX_AGE_ATTR;
return Cookie.MAX_AGE_ATTR;
}
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
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.ClientCookie;
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;
import org.apache.http.util.TextUtils;
/**
*
* @since 4.0
*/
@Immutable
public class NetscapeDomainHandler extends BasicDomainHandler {
public NetscapeDomainHandler() {
super();
}
@Override
public void parse(final SetCookie cookie, final String value) throws MalformedCookieException {
Args.notNull(cookie, "Cookie");
if (TextUtils.isBlank(value)) {
throw new MalformedCookieException("Blank or null value for domain attribute");
}
cookie.setDomain(value);
}
@Override
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
final String host = origin.getHost();
final String domain = cookie.getDomain();
if (!host.equals(domain) && !BasicDomainHandler.domainMatch(domain, host)) {
throw new CookieRestrictionViolationException(
"Illegal domain attribute \"" + domain + "\". Domain of origin: \"" + host + "\"");
}
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.ROOT);
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);
}
@Override
public String getAttributeName() {
return ClientCookie.DOMAIN_ATTR;
}
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.cookie;
import java.util.ArrayList;
import java.util.BitSet;
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.message.TokenParser;
import org.apache.http.util.Args;
import org.apache.http.util.CharArrayBuffer;
/**
*
* @since 4.0
*/
@Immutable
public class NetscapeDraftHeaderParser {
public final static NetscapeDraftHeaderParser DEFAULT = new NetscapeDraftHeaderParser();
private final static char PARAM_DELIMITER = ';';
// IMPORTANT!
// These private static variables must be treated as immutable and never exposed outside this class
private static final BitSet TOKEN_DELIMS = TokenParser.INIT_BITSET('=', PARAM_DELIMITER);
private static final BitSet VALUE_DELIMS = TokenParser.INIT_BITSET(PARAM_DELIMITER);
private final TokenParser tokenParser;
public NetscapeDraftHeaderParser() {
super();
this.tokenParser = TokenParser.INSTANCE;
}
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<NameValuePair> 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) {
final String name = tokenParser.parseToken(buffer, cursor, TOKEN_DELIMS);
if (cursor.atEnd()) {
return new BasicNameValuePair(name, null);
}
final int delim = buffer.charAt(cursor.getPos());
cursor.updatePos(cursor.getPos() + 1);
if (delim != '=') {
return new BasicNameValuePair(name, null);
}
final String value = tokenParser.parseToken(buffer, cursor, VALUE_DELIMS);
if (!cursor.atEnd()) {
cursor.updatePos(cursor.getPos() + 1);
}
return new BasicNameValuePair(name, value);
}
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
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.Obsolete;
import org.apache.http.annotation.ThreadSafe;
import org.apache.http.cookie.CommonCookieAttributeHandler;
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.
* <p>
* Rendered obsolete by {@link org.apache.http.impl.cookie.RFC6265LaxSpec}.
*
* @since 4.0
* @see org.apache.http.impl.cookie.RFC6265LaxSpec
*/
@Obsolete
@ThreadSafe
public class NetscapeDraftSpec extends CookieSpecBase {
protected static final String EXPIRES_PATTERN = "EEE, dd-MMM-yy HH:mm:ss z";
/** Default constructor */
public NetscapeDraftSpec(final String[] datepatterns) {
super(new BasicPathHandler(),
new NetscapeDomainHandler(),
new BasicSecureHandler(),
new BasicCommentHandler(),
new BasicExpiresHandler(
datepatterns != null ? datepatterns.clone() : new String[]{EXPIRES_PATTERN}));
}
NetscapeDraftSpec(final CommonCookieAttributeHandler... handlers) {
super(handlers);
}
public NetscapeDraftSpec() {
this((String[]) null);
}
/**
* Parses the Set-Cookie value into an array of {@code Cookie}s.
*
* <p>Syntax of the Set-Cookie HTTP Response Header:</p>
*
* <p>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.</p>
*
* <PRE>
* Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure
* </PRE>
*
* <p>Please note that the Netscape draft specification does not fully conform to the HTTP
* header format. Comma character if present in {@code Set-Cookie} will not be treated
* as a header element separator</p>
*
* @see <a href="http://web.archive.org/web/20020803110822/http://wp.netscape.com/newsref/std/cookie_spec.html">
* The Cookie Spec.</a>
*
* @param header the {@code Set-Cookie} received from the server
* @return an array of {@code Cookie}s parsed from the Set-Cookie value
* @throws MalformedCookieException if an exception occurs during parsing
*/
@Override
public List<Cookie> 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 NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.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);
}
@Override
public List<Header> formatCookies(final List<Cookie> 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<Header> headers = new ArrayList<>(1);
headers.add(new BufferedHeader(buffer));
return headers;
}
@Override
public int getVersion() {
return 0;
}
@Override
public Header getVersionHeader() {
return null;
}
@Override
public String toString() {
return "netscape";
}
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.cookie;
import org.apache.http.annotation.Immutable;
import org.apache.http.annotation.Obsolete;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.protocol.HttpContext;
/**
* {@link org.apache.http.cookie.CookieSpecProvider} implementation that provides an instance of
* {@link NetscapeDraftSpec}. The instance returned by this factory
* can be shared by multiple threads.
* <p>
* Rendered obsolete by {@link org.apache.http.impl.cookie.RFC6265CookieSpecProvider}
*
* @since 4.4
* @see org.apache.http.impl.cookie.RFC6265CookieSpecProvider
*/
@Obsolete
@Immutable
public class NetscapeDraftSpecProvider implements CookieSpecProvider {
private final String[] datepatterns;
private volatile CookieSpec cookieSpec;
public NetscapeDraftSpecProvider(final String[] datepatterns) {
super();
this.datepatterns = datepatterns;
}
public NetscapeDraftSpecProvider() {
this(null);
}
@Override
public CookieSpec create(final HttpContext context) {
if (cookieSpec == null) {
synchronized (this) {
if (cookieSpec == null) {
this.cookieSpec = new NetscapeDraftSpec(this.datepatterns);
}
}
}
return this.cookieSpec;
}
}

View File

@ -1,129 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists 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.impl.cookie;
import java.util.Locale;
import org.apache.http.annotation.Immutable;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
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 RFC2109DomainHandler implements CommonCookieAttributeHandler {
public RFC2109DomainHandler() {
super();
}
@Override
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().isEmpty()) {
throw new MalformedCookieException("Blank value for domain attribute");
}
cookie.setDomain(value);
}
@Override
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.ROOT);
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");
}
}
}
@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.equals(domain) || (domain.startsWith(".") && host.endsWith(domain));
}
@Override
public String getAttributeName() {
return ClientCookie.DOMAIN_ATTR;
}
}

View File

@ -1,243 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists 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.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.Obsolete;
import org.apache.http.annotation.ThreadSafe;
import org.apache.http.client.utils.DateUtils;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
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.
* <p>
* Rendered obsolete by {@link org.apache.http.impl.cookie.RFC6265StrictSpec}.
*
* @since 4.0
* @see org.apache.http.impl.cookie.RFC6265StrictSpec
*/
@Obsolete
@ThreadSafe
public class RFC2109Spec extends CookieSpecBase {
final static String[] DATE_PATTERNS = {
DateUtils.PATTERN_RFC1123,
DateUtils.PATTERN_RFC1036,
DateUtils.PATTERN_ASCTIME
};
private final boolean oneHeader;
/** Default constructor */
public RFC2109Spec(final String[] datepatterns, final boolean oneHeader) {
super(new RFC2109VersionHandler(),
new BasicPathHandler(),
new RFC2109DomainHandler(),
new BasicMaxAgeHandler(),
new BasicSecureHandler(),
new BasicCommentHandler(),
new BasicExpiresHandler(
datepatterns != null ? datepatterns.clone() : DATE_PATTERNS));
this.oneHeader = oneHeader;
}
/** Default constructor */
public RFC2109Spec() {
this(null, false);
}
protected RFC2109Spec(final boolean oneHeader,
final CommonCookieAttributeHandler... handlers) {
super(handlers);
this.oneHeader = oneHeader;
}
@Override
public List<Cookie> 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);
}
@Override
public List<Header> formatCookies(final List<Cookie> cookies) {
Args.notEmpty(cookies, "List of cookies");
List<Cookie> cookieList;
if (cookies.size() > 1) {
// Create a mutable copy and sort the copy.
cookieList = new ArrayList<>(cookies);
Collections.sort(cookieList, CookiePathComparator.INSTANCE);
} else {
cookieList = cookies;
}
if (this.oneHeader) {
return doFormatOneHeader(cookieList);
} else {
return doFormatManyHeaders(cookieList);
}
}
private List<Header> doFormatOneHeader(final List<Cookie> 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<Header> headers = new ArrayList<>(1);
headers.add(new BufferedHeader(buffer));
return headers;
}
private List<Header> doFormatManyHeaders(final List<Cookie> cookies) {
final List<Header> 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 {@code "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 {@code "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);
}
}
}
@Override
public int getVersion() {
return 1;
}
@Override
public Header getVersionHeader() {
return null;
}
@Override
public String toString() {
return "rfc2109";
}
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.cookie;
import org.apache.http.annotation.Immutable;
import org.apache.http.annotation.Obsolete;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.protocol.HttpContext;
/**
* {@link org.apache.http.cookie.CookieSpecProvider} implementation that provides an instance of
* {@link RFC2109Spec}. The instance returned by this factory
* can be shared by multiple threads.
* <p>
* Rendered obsolete by {@link org.apache.http.impl.cookie.RFC6265CookieSpecProvider}
*
* @since 4.4
* @see org.apache.http.impl.cookie.RFC6265CookieSpecProvider
*/
@Obsolete
@Immutable
public class RFC2109SpecProvider implements CookieSpecProvider {
private final PublicSuffixMatcher publicSuffixMatcher;
private final boolean oneHeader;
private volatile CookieSpec cookieSpec;
public RFC2109SpecProvider(final PublicSuffixMatcher publicSuffixMatcher, final boolean oneHeader) {
super();
this.oneHeader = oneHeader;
this.publicSuffixMatcher = publicSuffixMatcher;
}
public RFC2109SpecProvider(final PublicSuffixMatcher publicSuffixMatcher) {
this(publicSuffixMatcher, false);
}
public RFC2109SpecProvider() {
this(null, false);
}
@Override
public CookieSpec create(final HttpContext context) {
if (cookieSpec == null) {
synchronized (this) {
if (cookieSpec == null) {
this.cookieSpec = new RFC2109Spec(this.oneHeader,
new RFC2109VersionHandler(),
new BasicPathHandler(),
PublicSuffixDomainFilter.decorate(
new RFC2109DomainHandler(), this.publicSuffixMatcher),
new BasicMaxAgeHandler(),
new BasicSecureHandler(),
new BasicCommentHandler());
}
}
}
return this.cookieSpec;
}
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.cookie;
import org.apache.http.annotation.Immutable;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
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 RFC2109VersionHandler extends AbstractCookieAttributeHandler implements CommonCookieAttributeHandler {
public RFC2109VersionHandler() {
super();
}
@Override
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().isEmpty()) {
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");
}
}
@Override
public String getAttributeName() {
return ClientCookie.VERSION_ATTR;
}
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.cookie;
import org.apache.http.annotation.Immutable;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
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.cookie.SetCookie2;
/**
* {@code "CommentURL"} cookie attribute handler for RFC 2965 cookie spec.
*
* @since 4.0
*/
@Immutable
public class RFC2965CommentUrlAttributeHandler implements CommonCookieAttributeHandler {
public RFC2965CommentUrlAttributeHandler() {
super();
}
@Override
public void parse(final SetCookie cookie, final String commenturl)
throws MalformedCookieException {
if (cookie instanceof SetCookie2) {
final SetCookie2 cookie2 = (SetCookie2) cookie;
cookie2.setCommentURL(commenturl);
}
}
@Override
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
}
@Override
public boolean match(final Cookie cookie, final CookieOrigin origin) {
return true;
}
@Override
public String getAttributeName() {
return ClientCookie.COMMENTURL_ATTR;
}
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.cookie;
import org.apache.http.annotation.Immutable;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
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.cookie.SetCookie2;
/**
* {@code "Discard"} cookie attribute handler for RFC 2965 cookie spec.
*
* @since 4.0
*/
@Immutable
public class RFC2965DiscardAttributeHandler implements CommonCookieAttributeHandler {
public RFC2965DiscardAttributeHandler() {
super();
}
@Override
public void parse(final SetCookie cookie, final String commenturl)
throws MalformedCookieException {
if (cookie instanceof SetCookie2) {
final SetCookie2 cookie2 = (SetCookie2) cookie;
cookie2.setDiscard(true);
}
}
@Override
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
}
@Override
public boolean match(final Cookie cookie, final CookieOrigin origin) {
return true;
}
@Override
public String getAttributeName() {
return ClientCookie.DISCARD_ATTR;
}
}

View File

@ -1,194 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists 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.impl.cookie;
import java.util.Locale;
import org.apache.http.annotation.Immutable;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
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;
/**
* {@code "Domain"} cookie attribute handler for RFC 2965 cookie spec.
*
*
* @since 3.1
*/
@Immutable
public class RFC2965DomainAttributeHandler implements CommonCookieAttributeHandler {
public RFC2965DomainAttributeHandler() {
super();
}
/**
* Parse cookie domain attribute.
*/
@Override
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().isEmpty()) {
throw new MalformedCookieException(
"Blank value for domain attribute");
}
String s = domain;
s = s.toLowerCase(Locale.ROOT);
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.
* <p>
* Host A's name domain-matches host B's if
* </p>
* <ol>
* <li>their host name strings string-compare equal; or</li>
* <li>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.)</li>
* </ol>
*
* @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.
*/
@Override
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.ROOT);
if (cookie.getDomain() == null) {
throw new CookieRestrictionViolationException("Invalid cookie state: " +
"domain not specified");
}
final String cookieDomain = cookie.getDomain().toLowerCase(Locale.ROOT);
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.
*/
@Override
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.ROOT);
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;
}
@Override
public String getAttributeName() {
return ClientCookie.DOMAIN_ATTR;
}
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
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.CommonCookieAttributeHandler;
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.cookie.SetCookie2;
import org.apache.http.util.Args;
/**
* {@code "Port"} cookie attribute handler for RFC 2965 cookie spec.
*
* @since 4.0
*/
@Immutable
public class RFC2965PortAttributeHandler implements CommonCookieAttributeHandler {
public RFC2965PortAttributeHandler() {
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 {@code 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 {@code true} if the given port exists in
* the given ports list; {@code 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.
*/
@Override
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().isEmpty()) {
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.
*/
@Override
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.
*/
@Override
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;
}
@Override
public String getAttributeName() {
return ClientCookie.PORT_ATTR;
}
}

View File

@ -1,256 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists 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.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.Obsolete;
import org.apache.http.annotation.ThreadSafe;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
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.
* <p>
* Rendered obsolete by {@link org.apache.http.impl.cookie.RFC6265StrictSpec}.
*
* @since 4.0
* @see org.apache.http.impl.cookie.RFC6265StrictSpec
*/
@Obsolete
@ThreadSafe
public class RFC2965Spec extends RFC2109Spec {
/**
* Default constructor
*
*/
public RFC2965Spec() {
this(null, false);
}
public RFC2965Spec(final String[] datepatterns, final boolean oneHeader) {
super(oneHeader,
new RFC2965VersionAttributeHandler(),
new BasicPathHandler(),
new RFC2965DomainAttributeHandler(),
new RFC2965PortAttributeHandler(),
new BasicMaxAgeHandler(),
new BasicSecureHandler(),
new BasicCommentHandler(),
new BasicExpiresHandler(
datepatterns != null ? datepatterns.clone() : DATE_PATTERNS),
new RFC2965CommentUrlAttributeHandler(),
new RFC2965DiscardAttributeHandler());
}
RFC2965Spec(final boolean oneHeader,
final CommonCookieAttributeHandler... handlers) {
super(oneHeader, handlers);
}
@Override
public List<Cookie> 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<Cookie> parse(
final HeaderElement[] elems,
final CookieOrigin origin) throws MalformedCookieException {
return createCookies(elems, adjustEffectiveHost(origin));
}
private List<Cookie> createCookies(
final HeaderElement[] elems,
final CookieOrigin origin) throws MalformedCookieException {
final List<Cookie> cookies = new ArrayList<>(elems.length);
for (final HeaderElement headerelement : elems) {
final String name = headerelement.getName();
final String value = headerelement.getValue();
if (name == null || name.isEmpty()) {
throw new MalformedCookieException("Cookie name may not be empty");
}
final BasicClientCookie2 cookie = new BasicClientCookie2(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<String, NameValuePair> 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.ROOT), param);
}
for (final Map.Entry<String, NameValuePair> entry : attribmap.entrySet()) {
final NameValuePair attrib = entry.getValue();
final String s = attrib.getName().toLowerCase(Locale.ROOT);
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().isEmpty()) {
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.
* <p>
* 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";
}
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.cookie;
import org.apache.http.annotation.Immutable;
import org.apache.http.annotation.Obsolete;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.protocol.HttpContext;
/**
* {@link org.apache.http.cookie.CookieSpecProvider} implementation that provides an instance of
* {@link RFC2965Spec}. The instance returned by this factory can
* be shared by multiple threads.
* <p>
* Rendered obsolete by {@link org.apache.http.impl.cookie.RFC6265CookieSpecProvider}
*
* @since 4.4
* @see org.apache.http.impl.cookie.RFC6265CookieSpecProvider
*/
@Obsolete
@Immutable
public class RFC2965SpecProvider implements CookieSpecProvider {
private final PublicSuffixMatcher publicSuffixMatcher;
private final boolean oneHeader;
private volatile CookieSpec cookieSpec;
public RFC2965SpecProvider(final PublicSuffixMatcher publicSuffixMatcher, final boolean oneHeader) {
super();
this.oneHeader = oneHeader;
this.publicSuffixMatcher = publicSuffixMatcher;
}
public RFC2965SpecProvider(final PublicSuffixMatcher publicSuffixMatcher) {
this(publicSuffixMatcher, false);
}
public RFC2965SpecProvider() {
this(null, false);
}
@Override
public CookieSpec create(final HttpContext context) {
if (cookieSpec == null) {
synchronized (this) {
if (cookieSpec == null) {
this.cookieSpec = new RFC2965Spec(this.oneHeader,
new RFC2965VersionAttributeHandler(),
new BasicPathHandler(),
PublicSuffixDomainFilter.decorate(
new RFC2965DomainAttributeHandler(), this.publicSuffixMatcher),
new RFC2965PortAttributeHandler(),
new BasicMaxAgeHandler(),
new BasicSecureHandler(),
new BasicCommentHandler(),
new RFC2965CommentUrlAttributeHandler(),
new RFC2965DiscardAttributeHandler());
}
}
}
return this.cookieSpec;
}
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.cookie;
import org.apache.http.annotation.Immutable;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
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.cookie.SetCookie2;
import org.apache.http.util.Args;
/**
* {@code "Version"} cookie attribute handler for RFC 2965 cookie spec.
*
* @since 4.0
*/
@Immutable
public class RFC2965VersionAttributeHandler implements CommonCookieAttributeHandler {
public RFC2965VersionAttributeHandler() {
super();
}
/**
* Parse cookie version attribute.
*/
@Override
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.
*/
@Override
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.");
}
}
}
@Override
public boolean match(final Cookie cookie, final CookieOrigin origin) {
return true;
}
@Override
public String getAttributeName() {
return ClientCookie.VERSION_ATTR;
}
}

View File

@ -40,7 +40,6 @@ import java.util.concurrent.ConcurrentHashMap;
import org.apache.http.FormattedHeader;
import org.apache.http.Header;
import org.apache.http.annotation.ThreadSafe;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieAttributeHandler;
@ -168,8 +167,8 @@ public class RFC6265CookieSpec implements CookieSpec {
attribMap.put(paramName, paramValue);
}
// Ignore 'Expires' if 'Max-Age' is present
if (attribMap.containsKey(ClientCookie.MAX_AGE_ATTR)) {
attribMap.remove(ClientCookie.EXPIRES_ATTR);
if (attribMap.containsKey(Cookie.MAX_AGE_ATTR)) {
attribMap.remove(Cookie.EXPIRES_ATTR);
}
for (Map.Entry<String, String> entry: attribMap.entrySet()) {
@ -264,14 +263,4 @@ public class RFC6265CookieSpec implements CookieSpec {
return false;
}
@Override
public final int getVersion() {
return 0;
}
@Override
public final Header getVersionHeader() {
return null;
}
}

View File

@ -46,12 +46,9 @@ import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.cookie.SM;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.impl.cookie.BasicClientCookie2;
import org.apache.http.impl.cookie.DefaultCookieSpecProvider;
import org.apache.http.impl.cookie.IgnoreSpecProvider;
import org.apache.http.impl.cookie.NetscapeDraftSpec;
import org.apache.http.impl.cookie.NetscapeDraftSpecProvider;
import org.apache.http.impl.cookie.RFC2965SpecProvider;
import org.apache.http.impl.cookie.RFC6265CookieSpecProvider;
import org.apache.http.impl.cookie.RFC6265StrictSpec;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.protocol.HttpCoreContext;
import org.junit.Assert;
@ -69,21 +66,23 @@ public class TestRequestAddCookies {
public void setUp() {
this.target = new HttpHost("localhost.local", 80);
this.cookieStore = new BasicCookieStore();
final BasicClientCookie2 cookie1 = new BasicClientCookie2("name1", "value1");
cookie1.setVersion(1);
final BasicClientCookie cookie1 = new BasicClientCookie("name1", "value1");
cookie1.setDomain("localhost.local");
cookie1.setPath("/");
this.cookieStore.addCookie(cookie1);
final BasicClientCookie2 cookie2 = new BasicClientCookie2("name2", "value2");
cookie2.setVersion(1);
final BasicClientCookie cookie2 = new BasicClientCookie("name2", "value2");
cookie2.setDomain("localhost.local");
cookie2.setPath("/");
this.cookieStore.addCookie(cookie2);
final CookieSpecProvider laxCookiePolicyPRovider = new RFC6265CookieSpecProvider(
RFC6265CookieSpecProvider.CompatibilityLevel.RELAXED, null);
final CookieSpecProvider strictCookiePolicyPRovider = new RFC6265CookieSpecProvider(
RFC6265CookieSpecProvider.CompatibilityLevel.STRICT, null);
this.cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create()
.register(CookieSpecs.DEFAULT, new DefaultCookieSpecProvider())
.register(CookieSpecs.STANDARD, new RFC2965SpecProvider())
.register(CookieSpecs.NETSCAPE, new NetscapeDraftSpecProvider())
.register(CookieSpecs.DEFAULT, laxCookiePolicyPRovider)
.register(CookieSpecs.STANDARD, laxCookiePolicyPRovider)
.register(CookieSpecs.STANDARD_STRICT, strictCookiePolicyPRovider)
.register(CookieSpecs.IGNORE_COOKIES, new IgnoreSpecProvider())
.build();
}
@ -117,14 +116,10 @@ public class TestRequestAddCookies {
final HttpRequestInterceptor interceptor = new RequestAddCookies();
interceptor.process(request, context);
final Header[] headers1 = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers1);
Assert.assertEquals(2, headers1.length);
Assert.assertEquals("$Version=1; name1=\"value1\"", headers1[0].getValue());
Assert.assertEquals("$Version=1; name2=\"value2\"", headers1[1].getValue());
final Header[] headers2 = request.getHeaders(SM.COOKIE2);
Assert.assertNotNull(headers2);
Assert.assertEquals(0, headers2.length);
final Header[] headers = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.length);
Assert.assertEquals("name1=value1; name2=value2", headers[0].getValue());
final CookieOrigin cookieOrigin = context.getCookieOrigin();
Assert.assertNotNull(cookieOrigin);
@ -149,12 +144,9 @@ public class TestRequestAddCookies {
final HttpRequestInterceptor interceptor = new RequestAddCookies();
interceptor.process(request, context);
final Header[] headers1 = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers1);
Assert.assertEquals(0, headers1.length);
final Header[] headers2 = request.getHeaders(SM.COOKIE2);
Assert.assertNotNull(headers2);
Assert.assertEquals(0, headers2.length);
final Header[] headers = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers);
Assert.assertEquals(0, headers.length);
}
@Test
@ -172,12 +164,9 @@ public class TestRequestAddCookies {
final HttpRequestInterceptor interceptor = new RequestAddCookies();
interceptor.process(request, context);
final Header[] headers1 = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers1);
Assert.assertEquals(0, headers1.length);
final Header[] headers2 = request.getHeaders(SM.COOKIE2);
Assert.assertNotNull(headers2);
Assert.assertEquals(0, headers2.length);
final Header[] headers = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers);
Assert.assertEquals(0, headers.length);
}
@Test
@ -195,12 +184,9 @@ public class TestRequestAddCookies {
final HttpRequestInterceptor interceptor = new RequestAddCookies();
interceptor.process(request, context);
final Header[] headers1 = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers1);
Assert.assertEquals(0, headers1.length);
final Header[] headers2 = request.getHeaders(SM.COOKIE2);
Assert.assertNotNull(headers2);
Assert.assertEquals(0, headers2.length);
final Header[] headers = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers);
Assert.assertEquals(0, headers.length);
}
@Test
@ -218,12 +204,9 @@ public class TestRequestAddCookies {
final HttpRequestInterceptor interceptor = new RequestAddCookies();
interceptor.process(request, context);
final Header[] headers1 = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers1);
Assert.assertEquals(0, headers1.length);
final Header[] headers2 = request.getHeaders(SM.COOKIE2);
Assert.assertNotNull(headers2);
Assert.assertEquals(0, headers2.length);
final Header[] headers = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers);
Assert.assertEquals(0, headers.length);
}
@Test
@ -239,19 +222,16 @@ public class TestRequestAddCookies {
final HttpRequestInterceptor interceptor = new RequestAddCookies();
interceptor.process(request, context);
final Header[] headers1 = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers1);
Assert.assertEquals(0, headers1.length);
final Header[] headers2 = request.getHeaders(SM.COOKIE2);
Assert.assertNotNull(headers2);
Assert.assertEquals(0, headers2.length);
final Header[] headers = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers);
Assert.assertEquals(0, headers.length);
}
@Test
public void testAddCookiesUsingExplicitCookieSpec() throws Exception {
final HttpRequest request = new BasicHttpRequest("GET", "/");
final RequestConfig config = RequestConfig.custom()
.setCookieSpec(CookieSpecs.NETSCAPE).build();
.setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
final HttpRoute route = new HttpRoute(this.target, null, false);
final HttpClientContext context = HttpClientContext.create();
@ -265,7 +245,7 @@ public class TestRequestAddCookies {
interceptor.process(request, context);
final CookieSpec cookieSpec = context.getCookieSpec();
Assert.assertTrue(cookieSpec instanceof NetscapeDraftSpec);
Assert.assertTrue(cookieSpec instanceof RFC6265StrictSpec);
final Header[] headers1 = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers1);
@ -368,8 +348,7 @@ public class TestRequestAddCookies {
public void testExcludeExpiredCookies() throws Exception {
final HttpRequest request = new BasicHttpRequest("GET", "/");
final BasicClientCookie2 cookie3 = new BasicClientCookie2("name3", "value3");
cookie3.setVersion(1);
final BasicClientCookie cookie3 = new BasicClientCookie("name3", "value3");
cookie3.setDomain("localhost.local");
cookie3.setPath("/");
cookie3.setExpiryDate(new Date(System.currentTimeMillis() + 100));
@ -393,14 +372,10 @@ public class TestRequestAddCookies {
final HttpRequestInterceptor interceptor = new RequestAddCookies();
interceptor.process(request, context);
final Header[] headers1 = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers1);
Assert.assertEquals(2, headers1.length);
Assert.assertEquals("$Version=1; name1=\"value1\"", headers1[0].getValue());
Assert.assertEquals("$Version=1; name2=\"value2\"", headers1[1].getValue());
final Header[] headers2 = request.getHeaders(SM.COOKIE2);
Assert.assertNotNull(headers2);
Assert.assertEquals(0, headers2.length);
final Header[] headers = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.length);
Assert.assertEquals("name1=value1; name2=value2", headers[0].getValue());
Mockito.verify(this.cookieStore, Mockito.times(1)).clearExpired(Mockito.<Date>any());
}
@ -426,12 +401,9 @@ public class TestRequestAddCookies {
final HttpRequestInterceptor interceptor = new RequestAddCookies();
interceptor.process(request, context);
final Header[] headers1 = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers1);
Assert.assertEquals(0, headers1.length);
final Header[] headers2 = request.getHeaders(SM.COOKIE2);
Assert.assertNotNull(headers2);
Assert.assertEquals(0, headers2.length);
final Header[] headers = request.getHeaders(SM.COOKIE);
Assert.assertNotNull(headers);
Assert.assertEquals(0, headers.length);
}
// Helper method

View File

@ -37,7 +37,7 @@ import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.SM;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.DefaultCookieSpec;
import org.apache.http.impl.cookie.RFC6265LaxSpec;
import org.apache.http.message.BasicHttpResponse;
import org.junit.Assert;
import org.junit.Before;
@ -52,7 +52,7 @@ public class TestResponseProcessCookies {
@Before
public void setUp() throws Exception {
this.cookieOrigin = new CookieOrigin("localhost", 80, "/", false);
this.cookieSpec = new DefaultCookieSpec();
this.cookieSpec = new RFC6265LaxSpec();
this.cookieStore = new BasicCookieStore();
}
@ -87,7 +87,6 @@ public class TestResponseProcessCookies {
Assert.assertNotNull(cookies);
Assert.assertEquals(1, cookies.size());
final Cookie cookie = cookies.get(0);
Assert.assertEquals(0, cookie.getVersion());
Assert.assertEquals("name1", cookie.getName());
Assert.assertEquals("value1", cookie.getValue());
Assert.assertEquals("localhost", cookie.getDomain());
@ -148,65 +147,4 @@ public class TestResponseProcessCookies {
Assert.assertEquals(0, cookies.size());
}
@Test
public void testSetCookie2OverrideSetCookie() throws Exception {
final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
response.addHeader(SM.SET_COOKIE, "name1=value1");
response.addHeader(SM.SET_COOKIE2, "name1=value2; Version=1");
final HttpClientContext context = HttpClientContext.create();
context.setAttribute(HttpClientContext.COOKIE_ORIGIN, this.cookieOrigin);
context.setAttribute(HttpClientContext.COOKIE_SPEC, this.cookieSpec);
context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);
final HttpResponseInterceptor interceptor = new ResponseProcessCookies();
interceptor.process(response, context);
final List<Cookie> cookies = this.cookieStore.getCookies();
Assert.assertNotNull(cookies);
Assert.assertEquals(1, cookies.size());
final Cookie cookie = cookies.get(0);
Assert.assertEquals(1, cookie.getVersion());
Assert.assertEquals("name1", cookie.getName());
Assert.assertEquals("value2", cookie.getValue());
Assert.assertEquals("localhost.local", cookie.getDomain());
Assert.assertEquals("/", cookie.getPath());
}
@Test
public void testInvalidHeader() throws Exception {
final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
response.addHeader(SM.SET_COOKIE2, "name=value; Version=crap");
final HttpClientContext context = HttpClientContext.create();
context.setAttribute(HttpClientContext.COOKIE_ORIGIN, this.cookieOrigin);
context.setAttribute(HttpClientContext.COOKIE_SPEC, this.cookieSpec);
context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);
final HttpResponseInterceptor interceptor = new ResponseProcessCookies();
interceptor.process(response, context);
final List<Cookie> cookies = this.cookieStore.getCookies();
Assert.assertNotNull(cookies);
Assert.assertTrue(cookies.isEmpty());
}
@Test
public void testCookieRejected() throws Exception {
final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
response.addHeader(SM.SET_COOKIE2, "name=value; Domain=www.somedomain.com; Version=1");
final HttpClientContext context = HttpClientContext.create();
context.setAttribute(HttpClientContext.COOKIE_ORIGIN, this.cookieOrigin);
context.setAttribute(HttpClientContext.COOKIE_SPEC, this.cookieSpec);
context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);
final HttpResponseInterceptor interceptor = new ResponseProcessCookies();
interceptor.process(response, context);
final List<Cookie> cookies = this.cookieStore.getCookies();
Assert.assertNotNull(cookies);
Assert.assertTrue(cookies.isEmpty());
}
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.cookie;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link BasicClientCookie2}.
*/
public class TestBasicClientCookie2 {
@SuppressWarnings("unused")
@Test
public void testConstructor() {
final BasicClientCookie2 cookie = new BasicClientCookie2("name", "value");
Assert.assertEquals("name", cookie.getName());
Assert.assertEquals("value", cookie.getValue());
try {
new BasicClientCookie2(null, null);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {
//expected
}
}
@Test
public void testCloning() throws Exception {
final BasicClientCookie2 orig = new BasicClientCookie2("name", "value");
orig.setDomain("domain");
orig.setPath("/");
orig.setAttribute("attrib", "stuff");
orig.setPorts(new int[] {80, 8080});
final BasicClientCookie2 clone = (BasicClientCookie2) orig.clone();
Assert.assertEquals(orig.getName(), clone.getName());
Assert.assertEquals(orig.getValue(), clone.getValue());
Assert.assertEquals(orig.getDomain(), clone.getDomain());
Assert.assertEquals(orig.getPath(), clone.getPath());
Assert.assertEquals(orig.getAttribute("attrib"), clone.getAttribute("attrib"));
Assert.assertEquals(orig.getPorts().length, clone.getPorts().length);
Assert.assertEquals(orig.getPorts()[0], clone.getPorts()[0]);
Assert.assertEquals(orig.getPorts()[1], clone.getPorts()[1]);
}
@Test
public void testHTTPCLIENT_1031() throws Exception {
final BasicClientCookie2 orig = new BasicClientCookie2("name", "value");
orig.setDomain("domain");
orig.setPath("/");
orig.setAttribute("attrib", "stuff");
final BasicClientCookie2 clone = (BasicClientCookie2) orig.clone();
Assert.assertEquals(orig.getName(), clone.getName());
Assert.assertEquals(orig.getValue(), clone.getValue());
Assert.assertEquals(orig.getDomain(), clone.getDomain());
Assert.assertEquals(orig.getPath(), clone.getPath());
Assert.assertEquals(orig.getAttribute("attrib"), clone.getAttribute("attrib"));
Assert.assertNull(clone.getPorts());
}
@Test
public void testSerialization() throws Exception {
final BasicClientCookie2 orig = new BasicClientCookie2("name", "value");
orig.setDomain("domain");
orig.setPath("/");
orig.setAttribute("attrib", "stuff");
orig.setPorts(new int[] {80, 8080});
final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream();
final ObjectOutputStream outstream = new ObjectOutputStream(outbuffer);
outstream.writeObject(orig);
outstream.close();
final byte[] raw = outbuffer.toByteArray();
final ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw);
final ObjectInputStream instream = new ObjectInputStream(inbuffer);
final BasicClientCookie2 clone = (BasicClientCookie2) instream.readObject();
Assert.assertEquals(orig.getName(), clone.getName());
Assert.assertEquals(orig.getValue(), clone.getValue());
Assert.assertEquals(orig.getDomain(), clone.getDomain());
Assert.assertEquals(orig.getPath(), clone.getPath());
Assert.assertEquals(orig.getAttribute("attrib"), clone.getAttribute("attrib"));
final int[] expected = orig.getPorts();
final int[] clones = clone.getPorts();
Assert.assertNotNull(expected);
Assert.assertNotNull(clones);
Assert.assertEquals(expected.length, clones.length);
for (int i = 0; i < expected.length; i++) {
Assert.assertEquals(expected[i], clones[i]);
}
}
}

View File

@ -36,7 +36,7 @@ import java.util.Locale;
import org.apache.http.client.utils.DateUtils;
import org.apache.http.conn.util.DomainType;
import org.apache.http.conn.util.PublicSuffixMatcher;
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;
@ -142,7 +142,7 @@ public class TestBasicCookieAttribHandlers {
final CookieAttributeHandler h = new BasicDomainHandler();
cookie.setDomain("somedomain.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "somedomain.com");
cookie.setAttribute(Cookie.DOMAIN_ATTR, "somedomain.com");
Assert.assertTrue(h.match(cookie, origin));
cookie.setDomain(".somedomain.com");
@ -156,7 +156,7 @@ public class TestBasicCookieAttribHandlers {
final CookieAttributeHandler h = new BasicDomainHandler();
cookie.setDomain("somedomain.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "somedomain.com");
cookie.setAttribute(Cookie.DOMAIN_ATTR, "somedomain.com");
Assert.assertTrue(h.match(cookie, origin));
cookie.setDomain(".somedomain.com");
@ -173,7 +173,7 @@ public class TestBasicCookieAttribHandlers {
final CookieAttributeHandler h = new BasicDomainHandler();
cookie.setDomain("somedomain.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "somedomain.com");
cookie.setAttribute(Cookie.DOMAIN_ATTR, "somedomain.com");
Assert.assertTrue(h.match(cookie, origin));
}
@ -184,7 +184,7 @@ public class TestBasicCookieAttribHandlers {
final CookieAttributeHandler h = new BasicDomainHandler();
cookie.setDomain("somedoMain.Com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "somedoMain.Com");
cookie.setAttribute(Cookie.DOMAIN_ATTR, "somedoMain.Com");
Assert.assertTrue(h.match(cookie, origin));
}
@ -373,27 +373,6 @@ public class TestBasicCookieAttribHandlers {
}
}
@Test
public void testBasicCommentParse() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieAttributeHandler h = new BasicCommentHandler();
h.parse(cookie, "whatever");
Assert.assertEquals("whatever", cookie.getComment());
h.parse(cookie, null);
Assert.assertEquals(null, cookie.getComment());
}
@Test
public void testBasicCommentInvalidInput() throws Exception {
final CookieAttributeHandler h = new BasicCommentHandler();
try {
h.parse(null, null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
}
@Test
public void testBasicSecureParse() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
@ -500,33 +479,42 @@ public class TestBasicCookieAttribHandlers {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final PublicSuffixMatcher matcher = new PublicSuffixMatcher(DomainType.ICANN, Arrays.asList("co.uk", "com"), null);
final PublicSuffixDomainFilter h = new PublicSuffixDomainFilter(new RFC2109DomainHandler(), matcher);
final PublicSuffixDomainFilter h = new PublicSuffixDomainFilter(new BasicDomainHandler(), matcher);
cookie.setDomain(".co.uk");
cookie.setAttribute(Cookie.DOMAIN_ATTR, ".co.uk");
Assert.assertFalse(h.match(cookie, new CookieOrigin("apache.co.uk", 80, "/stuff", false)));
cookie.setDomain("co.uk");
cookie.setAttribute(Cookie.DOMAIN_ATTR, "co.uk");
Assert.assertFalse(h.match(cookie, new CookieOrigin("apache.co.uk", 80, "/stuff", false)));
cookie.setDomain(".co.com");
cookie.setAttribute(Cookie.DOMAIN_ATTR, ".co.com");
Assert.assertTrue(h.match(cookie, new CookieOrigin("apache.co.com", 80, "/stuff", false)));
cookie.setDomain("co.com");
Assert.assertFalse(h.match(cookie, new CookieOrigin("apache.co.com", 80, "/stuff", false)));
cookie.setAttribute(Cookie.DOMAIN_ATTR, "co.com");
Assert.assertTrue(h.match(cookie, new CookieOrigin("apache.co.com", 80, "/stuff", false)));
cookie.setDomain(".com");
cookie.setAttribute(Cookie.DOMAIN_ATTR, ".com");
Assert.assertFalse(h.match(cookie, new CookieOrigin("apache.com", 80, "/stuff", false)));
cookie.setDomain("com");
cookie.setAttribute(Cookie.DOMAIN_ATTR, "com");
Assert.assertFalse(h.match(cookie, new CookieOrigin("apache.com", 80, "/stuff", false)));
cookie.setDomain("apache.com");
cookie.setAttribute(Cookie.DOMAIN_ATTR, "apache.com");
Assert.assertTrue(h.match(cookie, new CookieOrigin("apache.com", 80, "/stuff", false)));
cookie.setDomain(".apache.com");
cookie.setAttribute(Cookie.DOMAIN_ATTR, ".apache.com");
Assert.assertTrue(h.match(cookie, new CookieOrigin("www.apache.com", 80, "/stuff", false)));
cookie.setDomain("localhost");
cookie.setAttribute(Cookie.DOMAIN_ATTR, "localhost");
Assert.assertTrue(h.match(cookie, new CookieOrigin("localhost", 80, "/stuff", false)));
}

View File

@ -1,315 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists 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.impl.cookie;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import org.apache.http.Header;
import org.apache.http.cookie.ClientCookie;
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.message.BasicHeader;
import org.junit.Assert;
import org.junit.Test;
/**
* Test cases for Netscape cookie draft
*/
public class TestCookieNetscapeDraft {
@Test
public void testParseAbsPath() throws Exception {
final Header header = new BasicHeader("Set-Cookie", "name1=value1;Path=/path/");
final CookieSpec cookiespec = new NetscapeDraftSpec();
final CookieOrigin origin = new CookieOrigin("host", 80, "/path/", true);
final List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
Assert.assertEquals("Found 1 cookies.",1,cookies.size());
Assert.assertEquals("Name","name1",cookies.get(0).getName());
Assert.assertEquals("Value","value1",cookies.get(0).getValue());
Assert.assertEquals("Domain","host",cookies.get(0).getDomain());
Assert.assertEquals("Path","/path/",cookies.get(0).getPath());
}
@Test
public void testParseAbsPath2() throws Exception {
final Header header = new BasicHeader("Set-Cookie", "name1=value1;Path=/");
final CookieSpec cookiespec = new NetscapeDraftSpec();
final CookieOrigin origin = new CookieOrigin("host", 80, "/", true);
final List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
Assert.assertEquals("Found 1 cookies.",1,cookies.size());
Assert.assertEquals("Name","name1",cookies.get(0).getName());
Assert.assertEquals("Value","value1",cookies.get(0).getValue());
Assert.assertEquals("Domain","host",cookies.get(0).getDomain());
Assert.assertEquals("Path","/",cookies.get(0).getPath());
}
@Test
public void testParseRelativePath() throws Exception {
final Header header = new BasicHeader("Set-Cookie", "name1=value1;Path=whatever");
final CookieSpec cookiespec = new NetscapeDraftSpec();
final CookieOrigin origin = new CookieOrigin("host", 80, "whatever", true);
final List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
Assert.assertEquals("Found 1 cookies.",1,cookies.size());
Assert.assertEquals("Name","name1",cookies.get(0).getName());
Assert.assertEquals("Value","value1",cookies.get(0).getValue());
Assert.assertEquals("Domain","host",cookies.get(0).getDomain());
Assert.assertEquals("Path","whatever",cookies.get(0).getPath());
}
@Test
public void testParseWithIllegalNetscapeDomain1() throws Exception {
final Header header = new BasicHeader("Set-Cookie","cookie-name=cookie-value; domain=.com");
final CookieSpec cookiespec = new NetscapeDraftSpec();
try {
final CookieOrigin origin = new CookieOrigin("a.com", 80, "/", false);
final List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
Assert.fail("MalformedCookieException exception should have been thrown");
} catch (final MalformedCookieException e) {
// expected
}
}
@Test
public void testParseWithWrongNetscapeDomain2() throws Exception {
final Header header = new BasicHeader("Set-Cookie","cookie-name=cookie-value; domain=.y.z");
final CookieSpec cookiespec = new NetscapeDraftSpec();
try {
final CookieOrigin origin = new CookieOrigin("x.y.z", 80, "/", false);
final List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
Assert.fail("MalformedCookieException exception should have been thrown");
} catch (final MalformedCookieException e) {
// expected
}
}
@Test
public void testParseVersionIgnored() throws Exception {
final Header header = new BasicHeader("Set-Cookie", "name1=value1;Path=/path/;Version=1;");
final CookieSpec cookiespec = new NetscapeDraftSpec();
final CookieOrigin origin = new CookieOrigin("host", 80, "/path/", true);
final List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
Assert.assertEquals("Found 1 cookies.",1,cookies.size());
final Cookie cookie = cookies.get(0);
Assert.assertEquals("Name","name1", cookie.getName());
Assert.assertEquals("Value", "value1", cookie.getValue());
Assert.assertEquals("Domain", "host", cookie.getDomain());
Assert.assertEquals("Path","/path/", cookie.getPath());
Assert.assertEquals(0, cookie.getVersion());
}
/**
* Tests Netscape specific cookie formatting.
*/
@Test
public void testNetscapeCookieFormatting() throws Exception {
final Header header = new BasicHeader(
"Set-Cookie", "name=value; path=/; domain=.mydomain.com");
final CookieSpec cookiespec = new NetscapeDraftSpec();
final CookieOrigin origin = new CookieOrigin("myhost.mydomain.com", 80, "/", false);
final List<Cookie> cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
final List<Header> headers = cookiespec.formatCookies(cookies);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("name=value", headers.get(0).getValue());
}
/**
* Tests Netscape specific expire attribute parsing.
*/
@Test
public void testNetscapeCookieExpireAttribute() throws Exception {
final CookieSpec cookiespec = new NetscapeDraftSpec();
final Header header = new BasicHeader("Set-Cookie",
"name=value; path=/; domain=.mydomain.com; expires=Thu, 01-Jan-2070 00:00:10 GMT; comment=no_comment");
final CookieOrigin origin = new CookieOrigin("myhost.mydomain.com", 80, "/", false);
final List<Cookie> cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
Assert.assertNotNull(cookies);
Assert.assertEquals(1, cookies.size());
final Cookie cookie = cookies.get(0);
final Calendar c = Calendar.getInstance();
c.setTimeZone(TimeZone.getTimeZone("GMT"));
c.setTime(cookie.getExpiryDate());
final int year = c.get(Calendar.YEAR);
Assert.assertEquals(2070, year);
}
/**
* Expire attribute with two digit year.
*/
@Test
public void testNetscapeCookieExpireAttributeTwoDigitYear() throws Exception {
final CookieSpec cookiespec = new NetscapeDraftSpec();
final Header header = new BasicHeader("Set-Cookie",
"name=value; path=/; domain=.mydomain.com; expires=Thursday, 01-Jan-70 00:00:10 GMT; comment=no_comment");
final CookieOrigin origin = new CookieOrigin("myhost.mydomain.com", 80, "/", false);
final List<Cookie> cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
Assert.assertNotNull(cookies);
Assert.assertEquals(1, cookies.size());
final Cookie cookie = cookies.get(0);
final Calendar c = Calendar.getInstance();
c.setTimeZone(TimeZone.getTimeZone("GMT"));
c.setTime(cookie.getExpiryDate());
final int year = c.get(Calendar.YEAR);
Assert.assertEquals(2070, year);
}
/**
* Invalid expire attribute.
*/
@Test
public void testNetscapeCookieInvalidExpireAttribute() throws Exception {
final CookieSpec cookiespec = new NetscapeDraftSpec();
final CookieOrigin origin = new CookieOrigin("myhost.mydomain.com", 80, "/", false);
final Header header = new BasicHeader("Set-Cookie",
"name=value; path=/; domain=.mydomain.com; expires=Thu 01-Jan-2070 00:00:10 GMT; comment=no_comment");
try {
final List<Cookie> cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
Assert.fail("MalformedCookieException exception should have been thrown");
} catch (final MalformedCookieException e) {
// expected
}
}
/**
* Tests Netscape specific expire attribute without a time zone.
*/
@Test
public void testNetscapeCookieExpireAttributeNoTimeZone() throws Exception {
final CookieSpec cookiespec = new NetscapeDraftSpec();
final Header header = new BasicHeader("Set-Cookie",
"name=value; expires=Thu, 01-Jan-2006 00:00:00 ");
final CookieOrigin origin = new CookieOrigin("myhost.mydomain.com", 80, "/", false);
try {
cookiespec.parse(header, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
}
/**
* Tests if cookie values with embedded comma are handled correctly.
*/
@Test
public void testCookieWithComma() throws Exception {
final Header header = new BasicHeader("Set-Cookie", "a=b,c");
final CookieSpec cookiespec = new NetscapeDraftSpec();
final CookieOrigin origin = new CookieOrigin("localhost", 80, "/", false);
final List<Cookie> cookies = cookiespec.parse(header, origin);
Assert.assertEquals("number of cookies", 1, cookies.size());
Assert.assertEquals("a", cookies.get(0).getName());
Assert.assertEquals("b,c", cookies.get(0).getValue());
}
@Test
public void testFormatCookies() throws Exception {
final BasicClientCookie c1 = new BasicClientCookie("name1", "value1");
c1.setDomain(".whatever.com");
c1.setAttribute(ClientCookie.DOMAIN_ATTR, c1.getDomain());
c1.setPath("/");
c1.setAttribute(ClientCookie.PATH_ATTR, c1.getPath());
final Cookie c2 = new BasicClientCookie("name2", "value2");
final Cookie c3 = new BasicClientCookie("name3", null);
final CookieSpec cookiespec = new NetscapeDraftSpec();
final List<Cookie> cookies = new ArrayList<>();
cookies.add(c1);
cookies.add(c2);
cookies.add(c3);
final List<Header> headers = cookiespec.formatCookies(cookies);
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("name1=value1; name2=value2; name3", headers.get(0).getValue());
}
@Test
public void testInvalidInput() throws Exception {
final CookieSpec cookiespec = new NetscapeDraftSpec();
try {
cookiespec.parse(null, null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
cookiespec.parse(new BasicHeader("Set-Cookie", "name=value"), null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
cookiespec.formatCookies(null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
final List<Cookie> cookies = new ArrayList<>();
cookiespec.formatCookies(cookies);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
}
}

View File

@ -1,488 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists 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.impl.cookie;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
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.CookieSpec;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.message.BasicHeader;
import org.junit.Assert;
import org.junit.Test;
/**
* Test cases for RFC2109 cookie spec
*/
public class TestCookieRFC2109Spec {
@SuppressWarnings("unused")
@Test
public void testConstructor() throws Exception {
new RFC2109Spec();
new RFC2109Spec(null, false);
new RFC2109Spec(new String[] { DateUtils.PATTERN_RFC1036 }, false);
}
@Test
public void testParseVersion() throws Exception {
final Header header = new BasicHeader("Set-Cookie","cookie-name=cookie-value; version=1");
final CookieSpec cookiespec = new RFC2109Spec();
final CookieOrigin origin = new CookieOrigin("127.0.0.1", 80, "/", false);
final List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
Assert.assertEquals("Found 1 cookie.",1,cookies.size());
Assert.assertEquals("Name","cookie-name",cookies.get(0).getName());
Assert.assertEquals("Value","cookie-value",cookies.get(0).getValue());
Assert.assertEquals("Version",1,cookies.get(0).getVersion());
}
/**
* Test domain equals host
*/
@Test
public void testCookiesomainEqualsHost() throws Exception {
final Header header = new BasicHeader("Set-Cookie",
"cookie-name=cookie-value; domain=www.b.com; version=1");
final CookieSpec cookiespec = new RFC2109Spec();
final CookieOrigin origin = new CookieOrigin("www.b.com", 80, "/", false);
final List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
Assert.assertNotNull(cookies);
Assert.assertEquals(1, cookies.size());
Assert.assertEquals("www.b.com", cookies.get(0).getDomain());
}
/**
* Domain does not start with a dot
*/
@Test
public void testParseWithIllegalDomain1() throws Exception {
final Header header = new BasicHeader("Set-Cookie",
"cookie-name=cookie-value; domain=a.b.com; version=1");
final CookieSpec cookiespec = new RFC2109Spec();
final CookieOrigin origin = new CookieOrigin("www.a.b.com", 80, "/", false);
try {
final List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException e) {
// expected
}
}
/**
* Domain must have alt least one embedded dot
*/
@Test
public void testParseWithIllegalDomain2() throws Exception {
final Header header = new BasicHeader("Set-Cookie",
"cookie-name=cookie-value; domain=.com; version=1");
final CookieSpec cookiespec = new RFC2109Spec();
final CookieOrigin origin = new CookieOrigin("b.com", 80, "/", false);
try {
final List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException e) {
// expected
}
}
/**
* Host minus domain may not contain any dots
*/
@Test
public void testParseWithIllegalDomain4() throws Exception {
final Header header = new BasicHeader("Set-Cookie",
"cookie-name=cookie-value; domain=.c.com; version=1");
final CookieSpec cookiespec = new RFC2109Spec();
final CookieOrigin origin = new CookieOrigin("a.b.c.com", 80, "/", false);
try {
final List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException e) {
// expected
}
}
/**
* Tests if that invalid second domain level cookie gets
* rejected in the strict mode, but gets accepted in the
* browser compatibility mode.
*/
@Test
public void testSecondDomainLevelCookie() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", null);
cookie.setDomain(".sourceforge.net");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, cookie.getDomain());
cookie.setPath("/");
cookie.setAttribute(ClientCookie.PATH_ATTR, cookie.getPath());
final CookieSpec cookiespec = new RFC2109Spec();
final CookieOrigin origin = new CookieOrigin("sourceforge.net", 80, "/", false);
try {
cookiespec.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException e) {
// Expected
}
}
@Test
public void testSecondDomainLevelCookieMatch() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", null);
cookie.setDomain(".sourceforge.net");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, cookie.getDomain());
cookie.setPath("/");
cookie.setAttribute(ClientCookie.PATH_ATTR, cookie.getPath());
final CookieSpec cookiespec = new RFC2109Spec();
final CookieOrigin origin = new CookieOrigin("sourceforge.net", 80, "/", false);
Assert.assertFalse(cookiespec.match(cookie, origin));
}
@Test
public void testParseWithWrongPath() throws Exception {
final Header header = new BasicHeader("Set-Cookie",
"cookie-name=cookie-value; domain=127.0.0.1; path=/not/just/root");
final CookieSpec cookiespec = new RFC2109Spec();
final CookieOrigin origin = new CookieOrigin("127.0.0.1", 80, "/", false);
try {
final List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
Assert.fail("MalformedCookieException exception should have been thrown");
} catch (final MalformedCookieException e) {
// expected
}
}
/**
* Tests if cookie constructor rejects cookie name containing blanks.
*/
@Test
public void testCookieNameWithBlanks() throws Exception {
final Header setcookie = new BasicHeader("Set-Cookie", "invalid name=");
final CookieSpec cookiespec = new RFC2109Spec();
final CookieOrigin origin = new CookieOrigin("127.0.0.1", 80, "/", false);
try {
final List<Cookie> cookies = cookiespec.parse(setcookie, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
Assert.fail("MalformedCookieException exception should have been thrown");
} catch (final MalformedCookieException e) {
// expected
}
}
/**
* Tests if cookie constructor rejects cookie name starting with $.
*/
@Test
public void testCookieNameStartingWithDollarSign() throws Exception {
final Header setcookie = new BasicHeader("Set-Cookie", "$invalid_name=");
final CookieSpec cookiespec = new RFC2109Spec();
final CookieOrigin origin = new CookieOrigin("127.0.0.1", 80, "/", false);
try {
final List<Cookie> cookies = cookiespec.parse(setcookie, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
Assert.fail("MalformedCookieException exception should have been thrown");
} catch (final MalformedCookieException e) {
// expected
}
}
/**
* Tests if default cookie validator rejects cookies originating from a host without domain
* where domain attribute does not match the host of origin
*/
@Test
public void testInvalidDomainWithSimpleHostName() throws Exception {
final CookieSpec cookiespec = new RFC2109Spec();
Header header = new BasicHeader("Set-Cookie",
"name=\"value\"; version=\"1\"; path=\"/\"; domain=\".mydomain.com\"");
final CookieOrigin origin1 = new CookieOrigin("host", 80, "/", false);
List<Cookie> cookies = cookiespec.parse(header, origin1);
try {
cookiespec.validate(cookies.get(0), origin1);
Assert.fail("MalformedCookieException must have thrown");
}
catch(final MalformedCookieException expected) {
}
final CookieOrigin origin2 = new CookieOrigin("host2", 80, "/", false);
header = new BasicHeader("Set-Cookie",
"name=\"value\"; version=\"1\"; path=\"/\"; domain=\"host1\"");
cookies = cookiespec.parse(header, origin2);
try {
cookiespec.validate(cookies.get(0), origin2);
Assert.fail("MalformedCookieException must have thrown");
}
catch(final MalformedCookieException expected) {
}
}
/**
* Tests if cookie values with embedded comma are handled correctly.
*/
@Test
public void testCookieWithComma() throws Exception {
final Header header = new BasicHeader("Set-Cookie", "a=b,c");
final CookieSpec cookiespec = new RFC2109Spec();
final CookieOrigin origin = new CookieOrigin("localhost", 80, "/", false);
final List<Cookie> cookies = cookiespec.parse(header, origin);
Assert.assertEquals("number of cookies", 2, cookies.size());
Assert.assertEquals("a", cookies.get(0).getName());
Assert.assertEquals("b", cookies.get(0).getValue());
Assert.assertEquals("c", cookies.get(1).getName());
Assert.assertEquals(null, cookies.get(1).getValue());
}
/**
* Tests RFC 2109 compiant cookie formatting.
*/
@Test
public void testRFC2109CookieFormatting() throws Exception {
final CookieSpec cookiespec = new RFC2109Spec(null, false);
Header header = new BasicHeader("Set-Cookie",
"name=\"value\"; version=1; path=\"/\"; domain=\".mydomain.com\"");
final CookieOrigin origin = new CookieOrigin("myhost.mydomain.com", 80, "/", false);
List<Cookie> cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
List<Header> headers = cookiespec.formatCookies(cookies);
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("$Version=1; name=\"value\"; $Path=\"/\"; $Domain=\".mydomain.com\"",
headers.get(0).getValue());
header = new BasicHeader( "Set-Cookie",
"name=value; path=/; domain=.mydomain.com");
cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
headers = cookiespec.formatCookies(cookies);
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("$Version=0; name=value; $Path=/; $Domain=.mydomain.com",
headers.get(0).getValue());
}
@Test
public void testRFC2109CookiesFormatting() throws Exception {
final CookieSpec cookiespec = new RFC2109Spec(null, true);
Header header = new BasicHeader("Set-Cookie",
"name1=value1; path=/; domain=.mydomain.com, " +
"name2=\"value2\"; version=\"1\"; path=\"/\"; domain=\".mydomain.com\"");
final CookieOrigin origin = new CookieOrigin("myhost.mydomain.com", 80, "/", false);
List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
Assert.assertNotNull(cookies);
Assert.assertEquals(2, cookies.size());
List<Header> headers = cookiespec.formatCookies(cookies);
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals(
"$Version=0; name1=value1; $Path=/; $Domain=.mydomain.com; " +
"name2=value2; $Path=/; $Domain=.mydomain.com",
headers.get(0).getValue());
header = new BasicHeader("Set-Cookie",
"name1=value1; version=1; path=/; domain=.mydomain.com, " +
"name2=\"value2\"; version=\"1\"; path=\"/\"; domain=\".mydomain.com\"");
cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
Assert.assertNotNull(cookies);
Assert.assertEquals(2, cookies.size());
headers = cookiespec.formatCookies(cookies);
Assert.assertEquals(
"$Version=1; name1=\"value1\"; $Path=\"/\"; $Domain=\".mydomain.com\"; " +
"name2=\"value2\"; $Path=\"/\"; $Domain=\".mydomain.com\"",
headers.get(0).getValue());
}
/**
* Tests if null cookie values are handled correctly.
*/
@Test
public void testNullCookieValueFormatting() {
final BasicClientCookie cookie = new BasicClientCookie("name", null);
cookie.setDomain(".whatever.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, cookie.getDomain());
cookie.setPath("/");
cookie.setAttribute(ClientCookie.PATH_ATTR, cookie.getPath());
final CookieSpec cookiespec = new RFC2109Spec();
List<Cookie> cookies = new ArrayList<>();
cookies.add(cookie);
List<Header> headers = cookiespec.formatCookies(cookies);
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("$Version=0; name=; $Path=/; $Domain=.whatever.com",
headers.get(0).getValue());
cookie.setVersion(1);
cookies = new ArrayList<>();
cookies.add(cookie);
headers = cookiespec.formatCookies(cookies);
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("$Version=1; name=; $Path=\"/\"; $Domain=\".whatever.com\"",
headers.get(0).getValue());
}
@Test
public void testCookieNullDomainNullPathFormatting() {
final BasicClientCookie cookie = new BasicClientCookie("name", null);
cookie.setPath("/");
cookie.setAttribute(ClientCookie.PATH_ATTR, cookie.getPath());
final CookieSpec cookiespec = new RFC2109Spec();
List<Cookie> cookies = new ArrayList<>();
cookies.add(cookie);
List<Header> headers = cookiespec.formatCookies(cookies);
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("$Version=0; name=; $Path=/", headers.get(0).getValue());
cookie.removeAttribute(ClientCookie.DOMAIN_ATTR);
cookie.removeAttribute(ClientCookie.PATH_ATTR);
cookies = new ArrayList<>();
cookies.add(cookie);
headers = cookiespec.formatCookies(cookies);
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("$Version=0; name=", headers.get(0).getValue());
}
@Test
public void testCookieOrderingByPath() {
final BasicClientCookie c1 = new BasicClientCookie("name1", "value1");
c1.setPath("/a/b/c");
c1.setAttribute(ClientCookie.PATH_ATTR, c1.getPath());
final BasicClientCookie c2 = new BasicClientCookie("name2", "value2");
c2.setPath("/a/b");
c2.setAttribute(ClientCookie.PATH_ATTR, c2.getPath());
final BasicClientCookie c3 = new BasicClientCookie("name3", "value3");
c3.setPath("/a");
c3.setAttribute(ClientCookie.PATH_ATTR, c3.getPath());
final BasicClientCookie c4 = new BasicClientCookie("name4", "value4");
c4.setPath("/");
c4.setAttribute(ClientCookie.PATH_ATTR, c4.getPath());
final CookieSpec cookiespec = new RFC2109Spec(null, true);
final List<Cookie> cookies = new ArrayList<>();
cookies.add(c2);
cookies.add(c4);
cookies.add(c1);
cookies.add(c3);
final List<Header> headers = cookiespec.formatCookies(cookies);
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
Assert.assertEquals("$Version=0; name1=value1; $Path=/a/b/c; " +
"name2=value2; $Path=/a/b; " +
"name3=value3; $Path=/a; " +
"name4=value4; $Path=/", headers.get(0).getValue());
}
@Test(expected=MalformedCookieException.class)
public void testVersion1CookieWithInvalidExpires() throws Exception {
final CookieSpec cookiespec = new RFC2109Spec();
final CookieOrigin origin = new CookieOrigin("myhost.mydomain.com", 80, "/", false);
final Header origHeader = new BasicHeader("Set-Cookie",
"test=\"test\"; Version=1; Expires=Mon, 11-Feb-2013 10:39:19 GMT; Path=/");
cookiespec.parse(origHeader, origin);
}
@Test
public void testInvalidInput() throws Exception {
final CookieSpec cookiespec = new RFC2109Spec();
try {
cookiespec.parse(null, null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
cookiespec.parse(new BasicHeader("Set-Cookie", "name=value"), null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
cookiespec.validate(null, null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
cookiespec.formatCookies(null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
final List<Cookie> cookies = new ArrayList<>();
cookiespec.formatCookies(cookies);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
}
}

View File

@ -1,299 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists 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.impl.cookie;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.cookie.ClientCookie;
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.SetCookie2;
import org.apache.http.message.BasicHeader;
import org.junit.Assert;
import org.junit.Test;
/**
* Test cases for 'best match' cookie policy
*/
public class TestDefaultCookieSpec {
@Test
public void testCookieBrowserCompatParsing() throws Exception {
final CookieSpec cookiespec = new DefaultCookieSpec();
final CookieOrigin origin = new CookieOrigin("a.b.domain.com", 80, "/", false);
// Make sure the lenient (browser compatible) cookie parsing
// and validation is used for Netscape style cookies
final Header header = new BasicHeader("Set-Cookie", "name=value;path=/;domain=domain.com");
final List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
}
@Test
public void testNetscapeCookieParsing() throws Exception {
final CookieSpec cookiespec = new DefaultCookieSpec();
final CookieOrigin origin = new CookieOrigin("myhost.mydomain.com", 80, "/", false);
Header header = new BasicHeader("Set-Cookie",
"name=value; path=/; domain=.mydomain.com; expires=Thu, 01-Jan-2070 00:00:10 GMT; comment=no_comment");
List<Cookie> cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
Assert.assertEquals(1, cookies.size());
header = new BasicHeader("Set-Cookie",
"name=value; path=/; domain=.mydomain.com; expires=Thu, 01-Jan-2070 00:00:10 GMT; version=1");
cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
Assert.assertEquals(1, cookies.size());
}
@Test
public void testCookieStandardCompliantParsing() throws Exception {
final CookieSpec cookiespec = new DefaultCookieSpec();
final CookieOrigin origin = new CookieOrigin("a.b.domain.com", 80, "/", false);
// Make sure the strict (RFC2965) cookie parsing
// and validation is used for version 1 Set-Cookie2 headers
Header header = new BasicHeader("Set-Cookie2", "name=value;path=/;domain=b.domain.com; version=1");
List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
// Make sure the strict (RFC2109) cookie parsing
// and validation is used for version 1 Set-Cookie headers
header = new BasicHeader("Set-Cookie", "name=value;path=/;domain=.b.domain.com; version=1");
cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
cookiespec.validate(cookies.get(i), origin);
}
header = new BasicHeader("Set-Cookie2", "name=value;path=/;domain=domain.com; version=1");
try {
cookies = cookiespec.parse(header, origin);
cookiespec.validate(cookies.get(0), origin);
Assert.fail("MalformedCookieException exception should have been thrown");
} catch (final MalformedCookieException e) {
// expected
}
}
@Test
public void testCookieStandardCompliantParsingLocalHost() throws Exception {
final CookieSpec cookiespec = new DefaultCookieSpec();
final CookieOrigin origin = new CookieOrigin("localhost", 80, "/", false);
final Header header = new BasicHeader("Set-Cookie", "special=\"abcdigh\"; Version=1");
final List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
final Cookie cookie = cookies.get(i);
cookiespec.validate(cookie, origin);
Assert.assertEquals("localhost", cookie.getDomain());
Assert.assertFalse(cookie instanceof SetCookie2);
}
}
@Test
public void testCookieStandardCompliantParsingLocalHost2() throws Exception {
final CookieSpec cookiespec = new DefaultCookieSpec();
final CookieOrigin origin = new CookieOrigin("localhost", 80, "/", false);
final Header header = new BasicHeader("Set-Cookie2", "special=\"abcdigh\"; Version=1");
final List<Cookie> cookies = cookiespec.parse(header, origin);
for (int i = 0; i < cookies.size(); i++) {
final Cookie cookie = cookies.get(i);
cookiespec.validate(cookie, origin);
Assert.assertEquals("localhost.local", cookie.getDomain());
Assert.assertTrue(cookie instanceof SetCookie2);
}
}
@Test
public void testCookieBrowserCompatMatch() throws Exception {
final CookieSpec cookiespec = new DefaultCookieSpec();
final CookieOrigin origin = new CookieOrigin("a.b.domain.com", 80, "/", false);
// Make sure the lenient (browser compatible) cookie matching
// is used for Netscape style cookies
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
cookie.setDomain(".domain.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, cookie.getDomain());
cookie.setPath("/");
cookie.setAttribute(ClientCookie.PATH_ATTR, cookie.getPath());
Assert.assertTrue(cookiespec.match(cookie, origin));
}
@Test
public void testCookieStandardCompliantMatch() throws Exception {
final CookieSpec cookiespec = new DefaultCookieSpec();
final CookieOrigin origin = new CookieOrigin("a.b.domain.com", 80, "/", false);
// Make sure the strict (RFC2965) cookie matching
// is used for version 1 cookies
final BasicClientCookie2 cookie = new BasicClientCookie2("name", "value");
cookie.setVersion(1);
cookie.setDomain(".domain.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, cookie.getDomain());
cookie.setPath("/");
cookie.setAttribute(ClientCookie.PATH_ATTR, cookie.getPath());
Assert.assertFalse(cookiespec.match(cookie, origin));
cookie.setDomain(".b.domain.com");
Assert.assertTrue(cookiespec.match(cookie, origin));
}
@Test
public void testCookieBrowserCompatFormatting() throws Exception {
final CookieSpec cookiespec = new DefaultCookieSpec();
// Make sure the lenient (browser compatible) cookie formatting
// is used for Netscape style cookies
final BasicClientCookie cookie1 = new BasicClientCookie("name1", "value1");
cookie1.setDomain(".domain.com");
cookie1.setAttribute(ClientCookie.DOMAIN_ATTR, cookie1.getDomain());
cookie1.setPath("/");
cookie1.setAttribute(ClientCookie.PATH_ATTR, cookie1.getPath());
final BasicClientCookie cookie2 = new BasicClientCookie("name2", "value2");
cookie2.setVersion(1);
cookie2.setDomain(".domain.com");
cookie2.setAttribute(ClientCookie.DOMAIN_ATTR, cookie2.getDomain());
cookie2.setPath("/");
cookie2.setAttribute(ClientCookie.PATH_ATTR, cookie2.getPath());
final List<Cookie> cookies = new ArrayList<>();
cookies.add(cookie1);
cookies.add(cookie2);
final List<Header> headers = cookiespec.formatCookies(cookies);
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
final Header header = headers.get(0);
Assert.assertEquals("name1=value1; name2=value2", header.getValue());
}
@Test
public void testCookieStandardCompliantFormatting() throws Exception {
final CookieSpec cookiespec = new DefaultCookieSpec(null, true);
// Make sure the strict (RFC2965) cookie formatting
// is used for Netscape style cookies
final BasicClientCookie cookie1 = new BasicClientCookie("name1", "value1");
cookie1.setVersion(1);
cookie1.setDomain(".domain.com");
cookie1.setAttribute(ClientCookie.DOMAIN_ATTR, cookie1.getDomain());
cookie1.setPath("/");
cookie1.setAttribute(ClientCookie.PATH_ATTR, cookie1.getPath());
final BasicClientCookie cookie2 = new BasicClientCookie("name2", "value2");
cookie2.setVersion(1);
cookie2.setDomain(".domain.com");
cookie2.setAttribute(ClientCookie.DOMAIN_ATTR, cookie2.getDomain());
cookie2.setPath("/");
cookie2.setAttribute(ClientCookie.PATH_ATTR, cookie2.getPath());
final List<Cookie> cookies = new ArrayList<>();
cookies.add(cookie1);
cookies.add(cookie2);
final List<Header> headers = cookiespec.formatCookies(cookies);
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
final Header header = headers.get(0);
Assert.assertEquals("$Version=1; name1=\"value1\"; $Path=\"/\"; $Domain=\".domain.com\"; " +
"name2=\"value2\"; $Path=\"/\"; $Domain=\".domain.com\"",
header.getValue());
}
@Test
public void testInvalidInput() throws Exception {
final CookieSpec cookiespec = new DefaultCookieSpec();
try {
cookiespec.parse(null, null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
cookiespec.parse(new BasicHeader("Set-Cookie", "name=value"), null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
cookiespec.formatCookies(null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
final List<Cookie> cookies = new ArrayList<>();
cookiespec.formatCookies(cookies);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
}
@Test
public void testVersion1CookieWithInvalidExpires() throws Exception {
final CookieSpec cookiespec = new DefaultCookieSpec();
final CookieOrigin origin = new CookieOrigin("myhost.mydomain.com", 80, "/", false);
final Header origHeader = new BasicHeader("Set-Cookie",
"test=\"test\"; Version=1; Expires=Mon, 11-Feb-2013 10:39:19 GMT; Path=/");
final List<Cookie> cookies = cookiespec.parse(origHeader, origin);
Assert.assertNotNull(cookies);
Assert.assertEquals(1, cookies.size());
final List<Header> headers = cookiespec.formatCookies(cookies);
Assert.assertNotNull(headers);
Assert.assertEquals(1, headers.size());
final Header header1 = headers.get(0);
Assert.assertEquals("test=\"test\"", header1.getValue());
}
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.cookie;
import org.apache.http.cookie.CookieAttributeHandler;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.MalformedCookieException;
import org.junit.Assert;
import org.junit.Test;
public class TestNetscapeCookieAttribHandlers {
@Test
public void testNetscapeDomainValidate1() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieOrigin origin = new CookieOrigin("somehost", 80, "/", false);
final CookieAttributeHandler h = new NetscapeDomainHandler();
cookie.setDomain("somehost");
h.validate(cookie, origin);
cookie.setDomain("otherhost");
try {
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
}
@Test
public void testNetscapeDomainValidate2() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieOrigin origin = new CookieOrigin("www.somedomain.com", 80, "/", false);
final CookieAttributeHandler h = new NetscapeDomainHandler();
cookie.setDomain(".somedomain.com");
h.validate(cookie, origin);
cookie.setDomain(".otherdomain.com");
try {
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
cookie.setDomain("www.otherdomain.com");
try {
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
}
@Test
public void testNetscapeDomainValidate3() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieOrigin origin = new CookieOrigin("www.a.com", 80, "/", false);
final CookieAttributeHandler h = new NetscapeDomainHandler();
cookie.setDomain(".a.com");
h.validate(cookie, origin);
cookie.setDomain(".com");
try {
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
}
@Test
public void testNetscapeDomainValidate4() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieOrigin origin = new CookieOrigin("www.a.b.c", 80, "/", false);
final CookieAttributeHandler h = new NetscapeDomainHandler();
cookie.setDomain(".a.b.c");
h.validate(cookie, origin);
cookie.setDomain(".b.c");
try {
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
}
@Test
public void testNetscapeDomainMatch1() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieOrigin origin = new CookieOrigin("www.somedomain.com", 80, "/", false);
final CookieAttributeHandler h = new NetscapeDomainHandler();
cookie.setDomain(null);
Assert.assertFalse(h.match(cookie, origin));
cookie.setDomain(".somedomain.com");
Assert.assertTrue(h.match(cookie, origin));
}
@Test
public void testNetscapeDomainMatch2() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieOrigin origin = new CookieOrigin("www.whatever.somedomain.com", 80, "/", false);
final CookieAttributeHandler h = new NetscapeDomainHandler();
cookie.setDomain(".somedomain.com");
Assert.assertTrue(h.match(cookie, origin));
}
@Test
public void testNetscapeDomainInvalidInput() throws Exception {
final CookieAttributeHandler h = new NetscapeDomainHandler();
try {
h.match(null, null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
h.match(new BasicClientCookie("name", "value"), null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
}
}

View File

@ -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
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.cookie;
import org.apache.http.HeaderElement;
import org.apache.http.NameValuePair;
import org.apache.http.message.ParserCursor;
import org.apache.http.util.CharArrayBuffer;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link NetscapeDraftHeaderParser}.
*/
public class TestNetscapeDraftHeaderParser {
@Test
public void testNetscapeCookieParsing() throws Exception {
final NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT;
String s = "name = value; test; test1 = stuff,with,commas ;" +
" test2 = \"stuff, stuff\"; test3=\"stuff";
CharArrayBuffer buffer = new CharArrayBuffer(16);
buffer.append(s);
ParserCursor cursor = new ParserCursor(0, s.length());
HeaderElement he = parser.parseHeader(buffer, cursor);
Assert.assertEquals("name", he.getName());
Assert.assertEquals("value", he.getValue());
final NameValuePair[] params = he.getParameters();
Assert.assertEquals("test", params[0].getName());
Assert.assertEquals(null, params[0].getValue());
Assert.assertEquals("test1", params[1].getName());
Assert.assertEquals("stuff,with,commas", params[1].getValue());
Assert.assertEquals("test2", params[2].getName());
Assert.assertEquals("\"stuff, stuff\"", params[2].getValue());
Assert.assertEquals("test3", params[3].getName());
Assert.assertEquals("\"stuff", params[3].getValue());
Assert.assertEquals(s.length(), cursor.getPos());
Assert.assertTrue(cursor.atEnd());
s = " ";
buffer = new CharArrayBuffer(16);
buffer.append(s);
cursor = new ParserCursor(0, s.length());
he = parser.parseHeader(buffer, cursor);
Assert.assertEquals("", he.getName());
Assert.assertEquals(null, he.getValue());
}
}

View File

@ -33,6 +33,7 @@ import java.io.InputStreamReader;
import org.apache.http.Consts;
import org.apache.http.conn.util.PublicSuffixList;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
import org.junit.Assert;
import org.junit.Before;
@ -57,13 +58,14 @@ public class TestPublicSuffixListParser {
in.close();
}
final PublicSuffixMatcher matcher = new PublicSuffixMatcher(suffixList.getRules(), suffixList.getExceptions());
this.filter = new PublicSuffixDomainFilter(new RFC2109DomainHandler(), matcher);
this.filter = new PublicSuffixDomainFilter(new BasicDomainHandler(), matcher);
}
@Test
public void testParse() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
cookie.setAttribute(Cookie.DOMAIN_ATTR, ".jp");
cookie.setDomain(".jp");
Assert.assertFalse(filter.match(cookie, new CookieOrigin("apache.jp", 80, "/stuff", false)));

View File

@ -1,298 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists 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.impl.cookie;
import org.apache.http.cookie.CookieAttributeHandler;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.MalformedCookieException;
import org.junit.Assert;
import org.junit.Test;
public class TestRFC2109CookieAttribHandlers {
@Test
public void testRFC2109DomainParse() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieAttributeHandler h = new RFC2109DomainHandler();
h.parse(cookie, "somehost");
Assert.assertEquals("somehost", cookie.getDomain());
try {
h.parse(cookie, null);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
try {
h.parse(cookie, " ");
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
}
@Test
public void testRFC2109DomainValidate1() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieOrigin origin = new CookieOrigin("somehost", 80, "/", false);
final CookieAttributeHandler h = new RFC2109DomainHandler();
cookie.setDomain("somehost");
h.validate(cookie, origin);
cookie.setDomain("otherhost");
try {
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
cookie.setDomain(null);
try {
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
}
@Test
public void testRFC2109DomainValidate2() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieOrigin origin = new CookieOrigin("www.somedomain.com", 80, "/", false);
final CookieAttributeHandler h = new RFC2109DomainHandler();
cookie.setDomain(".somedomain.com");
h.validate(cookie, origin);
cookie.setDomain(".otherdomain.com");
try {
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
cookie.setDomain("www.otherdomain.com");
try {
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
}
@Test
public void testRFC2109DomainValidate3() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieOrigin origin = new CookieOrigin("www.a.com", 80, "/", false);
final CookieAttributeHandler h = new RFC2109DomainHandler();
cookie.setDomain(".a.com");
h.validate(cookie, origin);
cookie.setDomain(".com");
try {
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
}
@Test
public void testRFC2109DomainValidate4() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieOrigin origin = new CookieOrigin("www.a.b.c", 80, "/", false);
final CookieAttributeHandler h = new RFC2109DomainHandler();
cookie.setDomain(".a.b.c");
h.validate(cookie, origin);
cookie.setDomain(".b.c");
try {
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
cookie.setDomain(".a.a.b.c");
try {
h.validate(cookie, origin);
Assert.fail("MalformedCookieException should have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
}
@Test
public void testRFC2109DomainMatch1() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieOrigin origin = new CookieOrigin("www.somedomain.com", 80, "/", false);
final CookieAttributeHandler h = new RFC2109DomainHandler();
cookie.setDomain(null);
Assert.assertFalse(h.match(cookie, origin));
cookie.setDomain(".somedomain.com");
Assert.assertTrue(h.match(cookie, origin));
}
@Test
public void testRFC2109DomainMatch2() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieOrigin origin = new CookieOrigin("www.whatever.somedomain.com", 80, "/", false);
final CookieAttributeHandler h = new RFC2109DomainHandler();
cookie.setDomain(".somedomain.com");
Assert.assertTrue(h.match(cookie, origin));
}
@Test
public void testRFC2109DomainMatch3() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieOrigin origin = new CookieOrigin("somedomain.com", 80, "/", false);
final CookieAttributeHandler h = new RFC2109DomainHandler();
cookie.setDomain("somedomain.com");
Assert.assertTrue(h.match(cookie, origin));
}
@Test
public void testRFC2109DomainMatch4() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieOrigin origin = new CookieOrigin("www.somedomain.com", 80, "/", false);
final CookieAttributeHandler h = new RFC2109DomainHandler();
cookie.setDomain("somedomain.com");
Assert.assertFalse(h.match(cookie, origin));
}
@Test
public void testRFC2109DomainInvalidInput() throws Exception {
final CookieAttributeHandler h = new RFC2109DomainHandler();
try {
h.parse(null, null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
h.validate(null, null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
h.validate(new BasicClientCookie("name", "value"), null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
h.match(null, null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
h.match(new BasicClientCookie("name", "value"), null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
}
@Test
public void testRFC2109VersionParse() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieAttributeHandler h = new RFC2109VersionHandler();
h.parse(cookie, "12");
Assert.assertEquals(12, cookie.getVersion());
}
@Test
public void testRFC2109VersionParseInvalid() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieAttributeHandler h = new RFC2109VersionHandler();
try {
h.parse(cookie, "garbage");
Assert.fail("MalformedCookieException must have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
try {
h.parse(cookie, null);
Assert.fail("MalformedCookieException must have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
try {
h.parse(cookie, " ");
Assert.fail("MalformedCookieException must have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
}
@Test
public void testRFC2109VersionValidate() throws Exception {
final BasicClientCookie cookie = new BasicClientCookie("name", "value");
final CookieOrigin origin = new CookieOrigin("somedomain.com", 80, "/", false);
final CookieAttributeHandler h = new RFC2109VersionHandler();
cookie.setVersion(12);
h.validate(cookie, origin);
cookie.setVersion(-12);
try {
h.validate(cookie, origin);
Assert.fail("MalformedCookieException must have been thrown");
} catch (final MalformedCookieException ex) {
// expected
}
}
@Test
public void testRFC2109VersionInvalidInput() throws Exception {
final CookieAttributeHandler h = new RFC2109VersionHandler();
try {
h.parse(null, null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
h.validate(null, null);
Assert.fail("IllegalArgumentException must have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
}
}

View File

@ -31,7 +31,6 @@ import java.util.Arrays;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.CommonCookieAttributeHandler;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
@ -63,10 +62,8 @@ public class TestRFC6265CookieSpec {
Assert.assertEquals("value", cookie.getValue());
Assert.assertEquals("/path", cookie.getPath());
Assert.assertEquals("host", cookie.getDomain());
Assert.assertTrue(cookie instanceof ClientCookie);
final ClientCookie clientCookie = (ClientCookie) cookie;
Assert.assertEquals("stuff", clientCookie.getAttribute("this"));
Assert.assertEquals(null, clientCookie.getAttribute("that"));
Assert.assertEquals("stuff", cookie.getAttribute("this"));
Assert.assertEquals(null, cookie.getAttribute("that"));
Mockito.verify(h1).parse(Mockito.<SetCookie>any(), Mockito.eq("stuff"));
Mockito.verify(h2, Mockito.never()).parse(Mockito.<SetCookie>any(), Mockito.anyString());
@ -84,9 +81,7 @@ public class TestRFC6265CookieSpec {
final Cookie cookie = cookies.get(0);
Assert.assertEquals("name", cookie.getName());
Assert.assertEquals(" one, two, three; four ", cookie.getValue());
Assert.assertTrue(cookie instanceof ClientCookie);
final ClientCookie clientCookie = (ClientCookie) cookie;
Assert.assertEquals("stuff", clientCookie.getAttribute("this"));
Assert.assertEquals("stuff", cookie.getAttribute("this"));
}
@Test(expected = MalformedCookieException.class)
@ -155,13 +150,11 @@ public class TestRFC6265CookieSpec {
final Cookie cookie = cookies.get(0);
Assert.assertEquals("name", cookie.getName());
Assert.assertEquals("value", cookie.getValue());
Assert.assertTrue(cookie instanceof ClientCookie);
final ClientCookie clientCookie = (ClientCookie) cookie;
Assert.assertEquals("v", clientCookie.getAttribute("p1"));
Assert.assertEquals("v,0", clientCookie.getAttribute("p2"));
Assert.assertTrue(clientCookie.containsAttribute("p3"));
Assert.assertTrue(clientCookie.containsAttribute("p4"));
Assert.assertFalse(clientCookie.containsAttribute("p5"));
Assert.assertEquals("v", cookie.getAttribute("p1"));
Assert.assertEquals("v,0", cookie.getAttribute("p2"));
Assert.assertTrue(cookie.containsAttribute("p3"));
Assert.assertTrue(cookie.containsAttribute("p4"));
Assert.assertFalse(cookie.containsAttribute("p5"));
}
@Test
@ -181,9 +174,7 @@ public class TestRFC6265CookieSpec {
final Cookie cookie = cookies.get(0);
Assert.assertEquals("name", cookie.getName());
Assert.assertEquals("value", cookie.getValue());
Assert.assertTrue(cookie instanceof ClientCookie);
final ClientCookie clientCookie = (ClientCookie) cookie;
Assert.assertEquals("v", clientCookie.getAttribute("p1"));
Assert.assertEquals("v", cookie.getAttribute("p1"));
}
@Test
@ -203,9 +194,7 @@ public class TestRFC6265CookieSpec {
final Cookie cookie = cookies.get(0);
Assert.assertEquals("name", cookie.getName());
Assert.assertEquals("value", cookie.getValue());
Assert.assertTrue(cookie instanceof ClientCookie);
final ClientCookie clientCookie = (ClientCookie) cookie;
Assert.assertEquals("", clientCookie.getAttribute("p1"));
Assert.assertEquals("", cookie.getAttribute("p1"));
}
@Test
@ -267,14 +256,6 @@ public class TestRFC6265CookieSpec {
Mockito.verify(h2, Mockito.never()).match(cookie, origin);
}
@Test
public void testLegacy() throws Exception {
final RFC6265CookieSpec cookiespec = new RFC6265CookieSpec();
Assert.assertEquals(0, cookiespec.getVersion());
Assert.assertEquals(null, cookiespec.getVersionHeader());
}
@Test
public void testFormatCookiesBasics() throws Exception {
final Cookie cookie1 = new BasicClientCookie("name1", "value");