提交 d4113561 编写于 作者: C chegar

7115150: java.net.HttpCookie code cleanup, style, formatting, typos

Reviewed-by: michaelm
上级 aec835c6
...@@ -31,17 +31,15 @@ import java.util.NoSuchElementException; ...@@ -31,17 +31,15 @@ import java.util.NoSuchElementException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.Date; import java.util.Date;
import java.lang.NullPointerException; // for javadoc
import java.util.Locale; import java.util.Locale;
import java.util.Objects; import java.util.Objects;
/** /**
* An HttpCookie object represents an http cookie, which carries state * An HttpCookie object represents an HTTP cookie, which carries state
* information between server and user agent. Cookie is widely adopted * information between server and user agent. Cookie is widely adopted
* to create stateful sessions. * to create stateful sessions.
* *
* <p>There are 3 http cookie specifications: * <p> There are 3 HTTP cookie specifications:
* <blockquote> * <blockquote>
* Netscape draft<br> * Netscape draft<br>
* RFC 2109 - <a href="http://www.ietf.org/rfc/rfc2109.txt"> * RFC 2109 - <a href="http://www.ietf.org/rfc/rfc2109.txt">
...@@ -50,25 +48,19 @@ import java.util.Objects; ...@@ -50,25 +48,19 @@ import java.util.Objects;
* <i>http://www.ietf.org/rfc/rfc2965.txt</i></a> * <i>http://www.ietf.org/rfc/rfc2965.txt</i></a>
* </blockquote> * </blockquote>
* *
* <p>HttpCookie class can accept all these 3 forms of syntax. * <p> HttpCookie class can accept all these 3 forms of syntax.
* *
* @author Edward Wang * @author Edward Wang
* @since 1.6 * @since 1.6
*/ */
public final class HttpCookie implements Cloneable { public final class HttpCookie implements Cloneable {
/* ---------------- Fields -------------- */ // ---------------- Fields --------------
//
// The value of the cookie itself. // The value of the cookie itself.
// private final String name; // NAME= ... "$Name" style is reserved
private String name; // NAME= ... "$Name" style is reserved
private String value; // value of NAME private String value; // value of NAME
//
// Attributes encoded in the header's cookie fields. // Attributes encoded in the header's cookie fields.
//
private String comment; // Comment=VALUE ... describes cookie's use private String comment; // Comment=VALUE ... describes cookie's use
private String commentURL; // CommentURL="http URL" ... describes cookie's use private String commentURL; // CommentURL="http URL" ... describes cookie's use
private boolean toDiscard; // Discard ... discard cookie unconditionally private boolean toDiscard; // Discard ... discard cookie unconditionally
...@@ -80,70 +72,61 @@ public final class HttpCookie implements Cloneable { ...@@ -80,70 +72,61 @@ public final class HttpCookie implements Cloneable {
private boolean httpOnly; // HttpOnly ... i.e. not accessible to scripts private boolean httpOnly; // HttpOnly ... i.e. not accessible to scripts
private int version = 1; // Version=1 ... RFC 2965 style private int version = 1; // Version=1 ... RFC 2965 style
//
// Hold the creation time (in seconds) of the http cookie for later // Hold the creation time (in seconds) of the http cookie for later
// expiration calculation // expiration calculation
// private final long whenCreated;
private long whenCreated = 0;
//
// Since the positive and zero max-age have their meanings, // Since the positive and zero max-age have their meanings,
// this value serves as a hint as 'not specify max-age' // this value serves as a hint as 'not specify max-age'
//
private final static long MAX_AGE_UNSPECIFIED = -1; private final static long MAX_AGE_UNSPECIFIED = -1;
//
// date formats used by Netscape's cookie draft // date formats used by Netscape's cookie draft
// as well as formats seen on various sites // as well as formats seen on various sites
//
private final static String[] COOKIE_DATE_FORMATS = { private final static String[] COOKIE_DATE_FORMATS = {
"EEE',' dd-MMM-yyyy HH:mm:ss 'GMT'", "EEE',' dd-MMM-yyyy HH:mm:ss 'GMT'",
"EEE',' dd MMM yyyy HH:mm:ss 'GMT'", "EEE',' dd MMM yyyy HH:mm:ss 'GMT'",
"EEE MMM dd yyyy HH:mm:ss 'GMT'Z" "EEE MMM dd yyyy HH:mm:ss 'GMT'Z"
}; };
//
// constant strings represent set-cookie header token // constant strings represent set-cookie header token
//
private final static String SET_COOKIE = "set-cookie:"; private final static String SET_COOKIE = "set-cookie:";
private final static String SET_COOKIE2 = "set-cookie2:"; private final static String SET_COOKIE2 = "set-cookie2:";
// ---------------- Ctors --------------
/* ---------------- Ctors -------------- */
/** /**
* Constructs a cookie with a specified name and value. * Constructs a cookie with a specified name and value.
* *
* <p>The name must conform to RFC 2965. That means it can contain * <p> The name must conform to RFC 2965. That means it can contain
* only ASCII alphanumeric characters and cannot contain commas, * only ASCII alphanumeric characters and cannot contain commas,
* semicolons, or white space or begin with a $ character. The cookie's * semicolons, or white space or begin with a $ character. The cookie's
* name cannot be changed after creation. * name cannot be changed after creation.
* *
* <p>The value can be anything the server chooses to send. Its * <p> The value can be anything the server chooses to send. Its
* value is probably of interest only to the server. The cookie's * value is probably of interest only to the server. The cookie's
* value can be changed after creation with the * value can be changed after creation with the
* <code>setValue</code> method. * {@code setValue} method.
* *
* <p>By default, cookies are created according to the RFC 2965 * <p> By default, cookies are created according to the RFC 2965
* cookie specification. The version can be changed with the * cookie specification. The version can be changed with the
* <code>setVersion</code> method. * {@code setVersion} method.
* *
* *
* @param name a <code>String</code> specifying the name of the cookie * @param name
* a {@code String} specifying the name of the cookie
* *
* @param value a <code>String</code> specifying the value of the cookie * @param value
* a {@code String} specifying the value of the cookie
*
* @throws IllegalArgumentException
* if the cookie name contains illegal characters or it is one of
* the tokens reserved for use by the cookie protocol
* @throws NullPointerException
* if {@code name} is {@code null}
* *
* @throws IllegalArgumentException if the cookie name contains illegal characters
* or it is one of the tokens reserved for use
* by the cookie protocol
* @throws NullPointerException if <tt>name</tt> is <tt>null</tt>
* @see #setValue * @see #setValue
* @see #setVersion * @see #setVersion
*
*/ */
public HttpCookie(String name, String value) { public HttpCookie(String name, String value) {
name = name.trim(); name = name.trim();
if (name.length() == 0 || !isToken(name) || isReserved(name)) { if (name.length() == 0 || !isToken(name) || isReserved(name)) {
...@@ -159,23 +142,25 @@ public final class HttpCookie implements Cloneable { ...@@ -159,23 +142,25 @@ public final class HttpCookie implements Cloneable {
portlist = null; portlist = null;
} }
/** /**
* Constructs cookies from set-cookie or set-cookie2 header string. * Constructs cookies from set-cookie or set-cookie2 header string.
* RFC 2965 section 3.2.2 set-cookie2 syntax indicates that one header line * RFC 2965 section 3.2.2 set-cookie2 syntax indicates that one header line
* may contain more than one cookie definitions, so this is a static * may contain more than one cookie definitions, so this is a static
* utility method instead of another constructor. * utility method instead of another constructor.
* *
* @param header a <tt>String</tt> specifying the set-cookie header. * @param header
* The header should start with "set-cookie", or "set-cookie2" * a {@code String} specifying the set-cookie header. The header
* token; or it should have no leading token at all. * should start with "set-cookie", or "set-cookie2" token; or it
* @return a List of cookie parsed from header line string * should have no leading token at all.
* @throws IllegalArgumentException if header string violates the cookie *
* specification's syntax, or the cookie * @return a List of cookie parsed from header line string
* name contains llegal characters, or *
* the cookie name is one of the tokens * @throws IllegalArgumentException
* reserved for use by the cookie protocol * if header string violates the cookie specification's syntax, or
* @throws NullPointerException if the header string is <tt>null</tt> * the cookie name contains illegal characters, or the cookie name
* is one of the tokens reserved for use by the cookie protocol
* @throws NullPointerException
* if the header string is {@code null}
*/ */
public static List<HttpCookie> parse(String header) { public static List<HttpCookie> parse(String header) {
int version = guessCookieVersion(header); int version = guessCookieVersion(header);
...@@ -187,10 +172,9 @@ public final class HttpCookie implements Cloneable { ...@@ -187,10 +172,9 @@ public final class HttpCookie implements Cloneable {
header = header.substring(SET_COOKIE.length()); header = header.substring(SET_COOKIE.length());
} }
List<HttpCookie> cookies = new java.util.ArrayList<>();
List<HttpCookie> cookies = new java.util.ArrayList<HttpCookie>(); // The Netscape cookie may have a comma in its expires attribute, while
// The Netscape cookie may have a comma in its expires attribute, // the comma is the delimiter in rfc 2965/2109 cookie header string.
// while the comma is the delimiter in rfc 2965/2109 cookie header string.
// so the parse logic is slightly different // so the parse logic is slightly different
if (version == 0) { if (version == 0) {
// Netscape draft cookie // Netscape draft cookie
...@@ -212,17 +196,13 @@ public final class HttpCookie implements Cloneable { ...@@ -212,17 +196,13 @@ public final class HttpCookie implements Cloneable {
return cookies; return cookies;
} }
// ---------------- Public operations --------------
/* ---------------- Public operations -------------- */
/** /**
* Reports whether this http cookie has expired or not. * Reports whether this HTTP cookie has expired or not.
* *
* @return <tt>true</tt> to indicate this http cookie has expired; * @return {@code true} to indicate this HTTP cookie has expired;
* otherwise, <tt>false</tt> * otherwise, {@code false}
*/ */
public boolean hasExpired() { public boolean hasExpired() {
if (maxAge == 0) return true; if (maxAge == 0) return true;
...@@ -240,155 +220,123 @@ public final class HttpCookie implements Cloneable { ...@@ -240,155 +220,123 @@ public final class HttpCookie implements Cloneable {
} }
/** /**
*
* Specifies a comment that describes a cookie's purpose. * Specifies a comment that describes a cookie's purpose.
* The comment is useful if the browser presents the cookie * The comment is useful if the browser presents the cookie
* to the user. Comments * to the user. Comments are not supported by Netscape Version 0 cookies.
* are not supported by Netscape Version 0 cookies.
* *
* @param purpose a <code>String</code> specifying the comment * @param purpose
* to display to the user * a {@code String} specifying the comment to display to the user
*
* @see #getComment
* *
* @see #getComment
*/ */
public void setComment(String purpose) { public void setComment(String purpose) {
comment = purpose; comment = purpose;
} }
/** /**
* Returns the comment describing the purpose of this cookie, or * Returns the comment describing the purpose of this cookie, or
* <code>null</code> if the cookie has no comment. * {@code null} if the cookie has no comment.
* *
* @return a <code>String</code> containing the comment, * @return a {@code String} containing the comment, or {@code null} if none
* or <code>null</code> if none
*
* @see #setComment
* *
* @see #setComment
*/ */
public String getComment() { public String getComment() {
return comment; return comment;
} }
/** /**
* Specifies a comment URL that describes a cookie's purpose.
* The comment URL is useful if the browser presents the cookie
* to the user. Comment URL is RFC 2965 only.
* *
* Specifies a comment url that describes a cookie's purpose. * @param purpose
* The comment url is useful if the browser presents the cookie * a {@code String} specifying the comment URL to display to the user
* to the user. Comment url is RFC 2965 only.
*
* @param purpose a <code>String</code> specifying the comment url
* to display to the user
*
* @see #getCommentURL
* *
* @see #getCommentURL
*/ */
public void setCommentURL(String purpose) { public void setCommentURL(String purpose) {
commentURL = purpose; commentURL = purpose;
} }
/** /**
* Returns the comment url describing the purpose of this cookie, or * Returns the comment URL describing the purpose of this cookie, or
* <code>null</code> if the cookie has no comment url. * {@code null} if the cookie has no comment URL.
*
* @return a <code>String</code> containing the comment url,
* or <code>null</code> if none
* *
* @see #setCommentURL * @return a {@code String} containing the comment URL, or {@code null}
* if none
* *
* @see #setCommentURL
*/ */
public String getCommentURL() { public String getCommentURL() {
return commentURL; return commentURL;
} }
/** /**
* Specify whether user agent should discard the cookie unconditionally. * Specify whether user agent should discard the cookie unconditionally.
* This is RFC 2965 only attribute. * This is RFC 2965 only attribute.
* *
* @param discard <tt>true</tt> indicates to discard cookie unconditionally * @param discard
* {@code true} indicates to discard cookie unconditionally
* *
* @see #getDiscard * @see #getDiscard
*/ */
public void setDiscard(boolean discard) { public void setDiscard(boolean discard) {
toDiscard = discard; toDiscard = discard;
} }
/** /**
* Return the discard attribute of the cookie * Returns the discard attribute of the cookie
* *
* @return a <tt>boolean</tt> to represent this cookie's discard attribute * @return a {@code boolean} to represent this cookie's discard attribute
* *
* @see #setDiscard * @see #setDiscard
*/ */
public boolean getDiscard() { public boolean getDiscard() {
return toDiscard; return toDiscard;
} }
/** /**
* Specify the portlist of the cookie, which restricts the port(s) * Specify the portlist of the cookie, which restricts the port(s)
* to which a cookie may be sent back in a Cookie header. * to which a cookie may be sent back in a Cookie header.
* *
* @param ports a <tt>String</tt> specify the port list, which is * @param ports
* comma seperated series of digits * a {@code String} specify the port list, which is comma separated
* @see #getPortlist * series of digits
*
* @see #getPortlist
*/ */
public void setPortlist(String ports) { public void setPortlist(String ports) {
portlist = ports; portlist = ports;
} }
/** /**
* Return the port list attribute of the cookie * Returns the port list attribute of the cookie
* *
* @return a <tt>String</tt> contains the port list * @return a {@code String} contains the port list or {@code null} if none
* or <tt>null</tt> if none *
* @see #setPortlist * @see #setPortlist
*/ */
public String getPortlist() { public String getPortlist() {
return portlist; return portlist;
} }
/** /**
*
* Specifies the domain within which this cookie should be presented. * Specifies the domain within which this cookie should be presented.
* *
* <p>The form of the domain name is specified by RFC 2965. A domain * <p> The form of the domain name is specified by RFC 2965. A domain
* name begins with a dot (<code>.foo.com</code>) and means that * name begins with a dot ({@code .foo.com}) and means that
* the cookie is visible to servers in a specified Domain Name System * the cookie is visible to servers in a specified Domain Name System
* (DNS) zone (for example, <code>www.foo.com</code>, but not * (DNS) zone (for example, {@code www.foo.com}, but not
* <code>a.b.foo.com</code>). By default, cookies are only returned * {@code a.b.foo.com}). By default, cookies are only returned
* to the server that sent them. * to the server that sent them.
* *
* @param pattern
* a {@code String} containing the domain name within which this
* cookie is visible; form is according to RFC 2965
* *
* @param pattern a <code>String</code> containing the domain name * @see #getDomain
* within which this cookie is visible;
* form is according to RFC 2965
*
* @see #getDomain
*
*/ */
public void setDomain(String pattern) { public void setDomain(String pattern) {
if (pattern != null) if (pattern != null)
domain = pattern.toLowerCase(); domain = pattern.toLowerCase();
...@@ -396,261 +344,187 @@ public final class HttpCookie implements Cloneable { ...@@ -396,261 +344,187 @@ public final class HttpCookie implements Cloneable {
domain = pattern; domain = pattern;
} }
/** /**
* Returns the domain name set for this cookie. The form of * Returns the domain name set for this cookie. The form of the domain name
* the domain name is set by RFC 2965. * is set by RFC 2965.
* *
* @return a <code>String</code> containing the domain name * @return a {@code String} containing the domain name
*
* @see #setDomain
* *
* @see #setDomain
*/ */
public String getDomain() { public String getDomain() {
return domain; return domain;
} }
/** /**
* Sets the maximum age of the cookie in seconds. * Sets the maximum age of the cookie in seconds.
* *
* <p>A positive value indicates that the cookie will expire * <p> A positive value indicates that the cookie will expire
* after that many seconds have passed. Note that the value is * after that many seconds have passed. Note that the value is
* the <i>maximum</i> age when the cookie will expire, not the cookie's * the <i>maximum</i> age when the cookie will expire, not the cookie's
* current age. * current age.
* *
* <p>A negative value means * <p> A negative value means that the cookie is not stored persistently
* that the cookie is not stored persistently and will be deleted * and will be deleted when the Web browser exits. A zero value causes the
* when the Web browser exits. A zero value causes the cookie * cookie to be deleted.
* to be deleted.
*
* @param expiry an integer specifying the maximum age of the
* cookie in seconds; if zero, the cookie
* should be discarded immediately;
* otherwise, the cookie's max age is unspecified.
* *
* @see #getMaxAge * @param expiry
* an integer specifying the maximum age of the cookie in seconds;
* if zero, the cookie should be discarded immediately; otherwise,
* the cookie's max age is unspecified.
* *
* @see #getMaxAge
*/ */
public void setMaxAge(long expiry) { public void setMaxAge(long expiry) {
maxAge = expiry; maxAge = expiry;
} }
/** /**
* Returns the maximum age of the cookie, specified in seconds. * Returns the maximum age of the cookie, specified in seconds. By default,
* By default, <code>-1</code> indicating the cookie will persist * {@code -1} indicating the cookie will persist until browser shutdown.
* until browser shutdown.
* *
* @return an integer specifying the maximum age of the cookie in seconds
* *
* @return an integer specifying the maximum age of the * @see #setMaxAge
* cookie in seconds
*
*
* @see #setMaxAge
*
*/ */
public long getMaxAge() { public long getMaxAge() {
return maxAge; return maxAge;
} }
/** /**
* Specifies a path for the cookie * Specifies a path for the cookie to which the client should return
* to which the client should return the cookie. * the cookie.
* *
* <p>The cookie is visible to all the pages in the directory * <p> The cookie is visible to all the pages in the directory
* you specify, and all the pages in that directory's subdirectories. * you specify, and all the pages in that directory's subdirectories.
* A cookie's path must include the servlet that set the cookie, * A cookie's path must include the servlet that set the cookie,
* for example, <i>/catalog</i>, which makes the cookie * for example, <i>/catalog</i>, which makes the cookie
* visible to all directories on the server under <i>/catalog</i>. * visible to all directories on the server under <i>/catalog</i>.
* *
* <p>Consult RFC 2965 (available on the Internet) for more * <p> Consult RFC 2965 (available on the Internet) for more
* information on setting path names for cookies. * information on setting path names for cookies.
* *
* @param uri
* a {@code String} specifying a path
* *
* @param uri a <code>String</code> specifying a path * @see #getPath
*
*
* @see #getPath
*
*/ */
public void setPath(String uri) { public void setPath(String uri) {
path = uri; path = uri;
} }
/** /**
* Returns the path on the server * Returns the path on the server to which the browser returns this cookie.
* to which the browser returns this cookie. The * The cookie is visible to all subpaths on the server.
* cookie is visible to all subpaths on the server.
* *
* @return a {@code String} specifying a path that contains a servlet name,
* for example, <i>/catalog</i>
* *
* @return a <code>String</code> specifying a path that contains * @see #setPath
* a servlet name, for example, <i>/catalog</i>
*
* @see #setPath
*
*/ */
public String getPath() { public String getPath() {
return path; return path;
} }
/** /**
* Indicates whether the cookie should only be sent using a secure protocol, * Indicates whether the cookie should only be sent using a secure protocol,
* such as HTTPS or SSL. * such as HTTPS or SSL.
* *
* <p>The default value is <code>false</code>. * <p> The default value is {@code false}.
*
* @param flag If <code>true</code>, the cookie can only be sent over
* a secure protocol like https.
* If <code>false</code>, it can be sent over any protocol.
* *
* @see #getSecure * @param flag
* If {@code true}, the cookie can only be sent over a secure
* protocol like HTTPS. If {@code false}, it can be sent over
* any protocol.
* *
* @see #getSecure
*/ */
public void setSecure(boolean flag) { public void setSecure(boolean flag) {
secure = flag; secure = flag;
} }
/** /**
* Returns <code>true</code> if sending this cookie should be * Returns {@code true} if sending this cookie should be restricted to a
* restricted to a secure protocol, or <code>false</code> if the * secure protocol, or {@code false} if the it can be sent using any
* it can be sent using any protocol. * protocol.
*
* @return <code>false</code> if the cookie can be sent over
* any standard protocol; otherwise, <code>true</code>
* *
* @see #setSecure * @return {@code false} if the cookie can be sent over any standard
* protocol; otherwise, <code>true</code>
* *
* @see #setSecure
*/ */
public boolean getSecure() { public boolean getSecure() {
return secure; return secure;
} }
/** /**
* Returns the name of the cookie. The name cannot be changed after * Returns the name of the cookie. The name cannot be changed after
* creation. * creation.
* *
* @return a <code>String</code> specifying the cookie's name * @return a {@code String} specifying the cookie's name
*
*/ */
public String getName() { public String getName() {
return name; return name;
} }
/** /**
*
* Assigns a new value to a cookie after the cookie is created. * Assigns a new value to a cookie after the cookie is created.
* If you use a binary value, you may want to use BASE64 encoding. * If you use a binary value, you may want to use BASE64 encoding.
* *
* <p>With Version 0 cookies, values should not contain white * <p> With Version 0 cookies, values should not contain white space,
* space, brackets, parentheses, equals signs, commas, * brackets, parentheses, equals signs, commas, double quotes, slashes,
* double quotes, slashes, question marks, at signs, colons, * question marks, at signs, colons, and semicolons. Empty values may not
* and semicolons. Empty values may not behave the same way * behave the same way on all browsers.
* on all browsers.
* *
* @param newValue a <code>String</code> specifying the new value * @param newValue
* * a {@code String} specifying the new value
*
* @see #getValue
* *
* @see #getValue
*/ */
public void setValue(String newValue) { public void setValue(String newValue) {
value = newValue; value = newValue;
} }
/** /**
* Returns the value of the cookie. * Returns the value of the cookie.
* *
* @return a <code>String</code> containing the cookie's * @return a {@code String} containing the cookie's present value
* present value
*
* @see #setValue
* *
* @see #setValue
*/ */
public String getValue() { public String getValue() {
return value; return value;
} }
/** /**
* Returns the version of the protocol this cookie complies * Returns the version of the protocol this cookie complies with. Version 1
* with. Version 1 complies with RFC 2965/2109, * complies with RFC 2965/2109, and version 0 complies with the original
* and version 0 complies with the original * cookie specification drafted by Netscape. Cookies provided by a browser
* cookie specification drafted by Netscape. Cookies provided * use and identify the browser's cookie version.
* by a browser use and identify the browser's cookie version.
*
* *
* @return 0 if the cookie complies with the * @return 0 if the cookie complies with the original Netscape
* original Netscape specification; 1 * specification; 1 if the cookie complies with RFC 2965/2109
* if the cookie complies with RFC 2965/2109
*
* @see #setVersion
* *
* @see #setVersion
*/ */
public int getVersion() { public int getVersion() {
return version; return version;
} }
/** /**
* Sets the version of the cookie protocol this cookie complies * Sets the version of the cookie protocol this cookie complies
* with. Version 0 complies with the original Netscape cookie * with. Version 0 complies with the original Netscape cookie
* specification. Version 1 complies with RFC 2965/2109. * specification. Version 1 complies with RFC 2965/2109.
* *
* @param v
* 0 if the cookie should comply with the original Netscape
* specification; 1 if the cookie should comply with RFC 2965/2109
* *
* @param v 0 if the cookie should comply with * @throws IllegalArgumentException
* the original Netscape specification; * if {@code v} is neither 0 nor 1
* 1 if the cookie should comply with RFC 2965/2109
*
* @throws IllegalArgumentException if <tt>v</tt> is neither 0 nor 1
*
* @see #getVersion
* *
* @see #getVersion
*/ */
public void setVersion(int v) { public void setVersion(int v) {
if (v != 0 && v != 1) { if (v != 0 && v != 1) {
throw new IllegalArgumentException("cookie version should be 0 or 1"); throw new IllegalArgumentException("cookie version should be 0 or 1");
...@@ -664,11 +538,11 @@ public final class HttpCookie implements Cloneable { ...@@ -664,11 +538,11 @@ public final class HttpCookie implements Cloneable {
* attribute. This means that the cookie should not be accessible to * attribute. This means that the cookie should not be accessible to
* scripting engines, like javascript. * scripting engines, like javascript.
* *
* @return {@code true} if this cookie should be considered http only. * @return {@code true} if this cookie should be considered HTTPOnly
* @see #setHttpOnly(boolean) *
* @see #setHttpOnly(boolean)
*/ */
public boolean isHttpOnly() public boolean isHttpOnly() {
{
return httpOnly; return httpOnly;
} }
...@@ -677,24 +551,25 @@ public final class HttpCookie implements Cloneable { ...@@ -677,24 +551,25 @@ public final class HttpCookie implements Cloneable {
* {@code true} it means the cookie should not be accessible to scripting * {@code true} it means the cookie should not be accessible to scripting
* engines like javascript. * engines like javascript.
* *
* @param httpOnly if {@code true} make the cookie HTTP only, i.e. * @param httpOnly
* only visible as part of an HTTP request. * if {@code true} make the cookie HTTP only, i.e. only visible as
* @see #isHttpOnly() * part of an HTTP request.
*
* @see #isHttpOnly()
*/ */
public void setHttpOnly(boolean httpOnly) public void setHttpOnly(boolean httpOnly) {
{
this.httpOnly = httpOnly; this.httpOnly = httpOnly;
} }
/** /**
* The utility method to check whether a host name is in a domain * The utility method to check whether a host name is in a domain or not.
* or not.
* *
* <p>This concept is described in the cookie specification. * <p> This concept is described in the cookie specification.
* To understand the concept, some terminologies need to be defined first: * To understand the concept, some terminologies need to be defined first:
* <blockquote> * <blockquote>
* effective host name = hostname if host name contains dot<br> * effective host name = hostname if host name contains dot<br>
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;or = hostname.local if not * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;or = hostname.local if not
* </blockquote> * </blockquote>
* <p>Host A's name domain-matches host B's if: * <p>Host A's name domain-matches host B's if:
* <blockquote><ul> * <blockquote><ul>
...@@ -731,9 +606,13 @@ public final class HttpCookie implements Cloneable { ...@@ -731,9 +606,13 @@ public final class HttpCookie implements Cloneable {
* host is example.local, and example.local domain-matches .local.</li> * host is example.local, and example.local domain-matches .local.</li>
* </ul></blockquote> * </ul></blockquote>
* *
* @param domain the domain name to check host name with * @param domain
* @param host the host name in question * the domain name to check host name with
* @return <tt>true</tt> if they domain-matches; <tt>false</tt> if not *
* @param host
* the host name in question
*
* @return {@code true} if they domain-matches; {@code false} if not
*/ */
public static boolean domainMatches(String domain, String host) { public static boolean domainMatches(String domain, String host) {
if (domain == null || host == null) if (domain == null || host == null)
...@@ -745,7 +624,8 @@ public final class HttpCookie implements Cloneable { ...@@ -745,7 +624,8 @@ public final class HttpCookie implements Cloneable {
if (embeddedDotInDomain == 0) if (embeddedDotInDomain == 0)
embeddedDotInDomain = domain.indexOf('.', 1); embeddedDotInDomain = domain.indexOf('.', 1);
if (!isLocalDomain if (!isLocalDomain
&& (embeddedDotInDomain == -1 || embeddedDotInDomain == domain.length() - 1)) && (embeddedDotInDomain == -1 ||
embeddedDotInDomain == domain.length() - 1))
return false; return false;
// if the host name contains no dot and the domain name // if the host name contains no dot and the domain name
...@@ -779,7 +659,6 @@ public final class HttpCookie implements Cloneable { ...@@ -779,7 +659,6 @@ public final class HttpCookie implements Cloneable {
return false; return false;
} }
/** /**
* Constructs a cookie header string representation of this cookie, * Constructs a cookie header string representation of this cookie,
* which is in the format defined by corresponding cookie specification, * which is in the format defined by corresponding cookie specification,
...@@ -796,17 +675,15 @@ public final class HttpCookie implements Cloneable { ...@@ -796,17 +675,15 @@ public final class HttpCookie implements Cloneable {
} }
} }
/** /**
* Test the equality of two http cookies. * Test the equality of two HTTP cookies.
* *
* <p> The result is <tt>true</tt> only if two cookies * <p> The result is {@code true} only if two cookies come from same domain
* come from same domain (case-insensitive), * (case-insensitive), have same name (case-insensitive), and have same path
* have same name (case-insensitive), * (case-sensitive).
* and have same path (case-sensitive).
* *
* @return <tt>true</tt> if 2 http cookies equal to each other; * @return {@code true} if two HTTP cookies equal to each other;
* otherwise, <tt>false</tt> * otherwise, {@code false}
*/ */
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
...@@ -825,19 +702,17 @@ public final class HttpCookie implements Cloneable { ...@@ -825,19 +702,17 @@ public final class HttpCookie implements Cloneable {
Objects.equals(getPath(), other.getPath()); Objects.equals(getPath(), other.getPath());
} }
/** /**
* Return hash code of this http cookie. The result is the sum of * Returns the hash code of this HTTP cookie. The result is the sum of
* hash code value of three significant components of this cookie: * hash code value of three significant components of this cookie: name,
* name, domain, and path. * domain, and path. That is, the hash code is the value of the expression:
* That is, the hash code is the value of the expression:
* <blockquote> * <blockquote>
* getName().toLowerCase().hashCode()<br> * getName().toLowerCase().hashCode()<br>
* + getDomain().toLowerCase().hashCode()<br> * + getDomain().toLowerCase().hashCode()<br>
* + getPath().hashCode() * + getPath().hashCode()
* </blockquote> * </blockquote>
* *
* @return this http cookie's hash code * @return this HTTP cookie's hash code
*/ */
@Override @Override
public int hashCode() { public int hashCode() {
...@@ -851,7 +726,7 @@ public final class HttpCookie implements Cloneable { ...@@ -851,7 +726,7 @@ public final class HttpCookie implements Cloneable {
/** /**
* Create and return a copy of this object. * Create and return a copy of this object.
* *
* @return a clone of this http cookie * @return a clone of this HTTP cookie
*/ */
@Override @Override
public Object clone() { public Object clone() {
...@@ -862,8 +737,7 @@ public final class HttpCookie implements Cloneable { ...@@ -862,8 +737,7 @@ public final class HttpCookie implements Cloneable {
} }
} }
// ---------------- Private operations --------------
/* ---------------- Private operations -------------- */
// Note -- disabled for now to allow full Netscape compatibility // Note -- disabled for now to allow full Netscape compatibility
// from RFC 2068, token special case characters // from RFC 2068, token special case characters
...@@ -872,15 +746,14 @@ public final class HttpCookie implements Cloneable { ...@@ -872,15 +746,14 @@ public final class HttpCookie implements Cloneable {
private static final String tspecials = ",;"; private static final String tspecials = ",;";
/* /*
* Tests a string and returns true if the string counts as a * Tests a string and returns true if the string counts as a token.
* token.
* *
* @param value the <code>String</code> to be tested * @param value
* the {@code String} to be tested
* *
* @return <code>true</code> if the <code>String</code> is * @return {@code true} if the {@code String} is a token;
* a token; <code>false</code> if it is not * {@code false} if it is not
*/ */
private static boolean isToken(String value) { private static boolean isToken(String value) {
int len = value.length(); int len = value.length();
...@@ -893,11 +766,12 @@ public final class HttpCookie implements Cloneable { ...@@ -893,11 +766,12 @@ public final class HttpCookie implements Cloneable {
return true; return true;
} }
/* /*
* @param name the name to be tested * @param name
* @return <tt>true</tt> if the name is reserved by cookie * the name to be tested
* specification, <tt>false</tt> if it is not *
* @return {@code true} if the name is reserved by cookie specification,
* {@code false} if it is not
*/ */
private static boolean isReserved(String name) { private static boolean isReserved(String name) {
if (name.equalsIgnoreCase("Comment") if (name.equalsIgnoreCase("Comment")
...@@ -919,16 +793,16 @@ public final class HttpCookie implements Cloneable { ...@@ -919,16 +793,16 @@ public final class HttpCookie implements Cloneable {
return false; return false;
} }
/* /*
* Parse header string to cookie object. * Parse header string to cookie object.
* *
* @param header header string; should contain only one NAME=VALUE pair * @param header
* header string; should contain only one NAME=VALUE pair
* *
* @return an HttpCookie being extracted * @return an HttpCookie being extracted
* *
* @throws IllegalArgumentException if header string violates the cookie * @throws IllegalArgumentException
* specification * if header string violates the cookie specification
*/ */
private static HttpCookie parseInternal(String header) private static HttpCookie parseInternal(String header)
{ {
...@@ -974,69 +848,97 @@ public final class HttpCookie implements Cloneable { ...@@ -974,69 +848,97 @@ public final class HttpCookie implements Cloneable {
return cookie; return cookie;
} }
/* /*
* assign cookie attribute value to attribute name; * assign cookie attribute value to attribute name;
* use a map to simulate method dispatch * use a map to simulate method dispatch
*/ */
static interface CookieAttributeAssignor { static interface CookieAttributeAssignor {
public void assign(HttpCookie cookie, String attrName, String attrValue); public void assign(HttpCookie cookie,
String attrName,
String attrValue);
} }
static java.util.Map<String, CookieAttributeAssignor> assignors = null; static final java.util.Map<String, CookieAttributeAssignor> assignors =
new java.util.HashMap<>();
static { static {
assignors = new java.util.HashMap<String, CookieAttributeAssignor>(); assignors.put("comment", new CookieAttributeAssignor() {
assignors.put("comment", new CookieAttributeAssignor(){ public void assign(HttpCookie cookie,
public void assign(HttpCookie cookie, String attrName, String attrValue) { String attrName,
if (cookie.getComment() == null) cookie.setComment(attrValue); String attrValue) {
if (cookie.getComment() == null)
cookie.setComment(attrValue);
} }
}); });
assignors.put("commenturl", new CookieAttributeAssignor(){ assignors.put("commenturl", new CookieAttributeAssignor() {
public void assign(HttpCookie cookie, String attrName, String attrValue) { public void assign(HttpCookie cookie,
if (cookie.getCommentURL() == null) cookie.setCommentURL(attrValue); String attrName,
String attrValue) {
if (cookie.getCommentURL() == null)
cookie.setCommentURL(attrValue);
} }
}); });
assignors.put("discard", new CookieAttributeAssignor(){ assignors.put("discard", new CookieAttributeAssignor() {
public void assign(HttpCookie cookie, String attrName, String attrValue) { public void assign(HttpCookie cookie,
String attrName,
String attrValue) {
cookie.setDiscard(true); cookie.setDiscard(true);
} }
}); });
assignors.put("domain", new CookieAttributeAssignor(){ assignors.put("domain", new CookieAttributeAssignor(){
public void assign(HttpCookie cookie, String attrName, String attrValue) { public void assign(HttpCookie cookie,
if (cookie.getDomain() == null) cookie.setDomain(attrValue); String attrName,
String attrValue) {
if (cookie.getDomain() == null)
cookie.setDomain(attrValue);
} }
}); });
assignors.put("max-age", new CookieAttributeAssignor(){ assignors.put("max-age", new CookieAttributeAssignor(){
public void assign(HttpCookie cookie, String attrName, String attrValue) { public void assign(HttpCookie cookie,
String attrName,
String attrValue) {
try { try {
long maxage = Long.parseLong(attrValue); long maxage = Long.parseLong(attrValue);
if (cookie.getMaxAge() == MAX_AGE_UNSPECIFIED) cookie.setMaxAge(maxage); if (cookie.getMaxAge() == MAX_AGE_UNSPECIFIED)
cookie.setMaxAge(maxage);
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {
throw new IllegalArgumentException("Illegal cookie max-age attribute"); throw new IllegalArgumentException(
"Illegal cookie max-age attribute");
} }
} }
}); });
assignors.put("path", new CookieAttributeAssignor(){ assignors.put("path", new CookieAttributeAssignor(){
public void assign(HttpCookie cookie, String attrName, String attrValue) { public void assign(HttpCookie cookie,
if (cookie.getPath() == null) cookie.setPath(attrValue); String attrName,
String attrValue) {
if (cookie.getPath() == null)
cookie.setPath(attrValue);
} }
}); });
assignors.put("port", new CookieAttributeAssignor(){ assignors.put("port", new CookieAttributeAssignor(){
public void assign(HttpCookie cookie, String attrName, String attrValue) { public void assign(HttpCookie cookie,
if (cookie.getPortlist() == null) cookie.setPortlist(attrValue == null ? "" : attrValue); String attrName,
String attrValue) {
if (cookie.getPortlist() == null)
cookie.setPortlist(attrValue == null ? "" : attrValue);
} }
}); });
assignors.put("secure", new CookieAttributeAssignor(){ assignors.put("secure", new CookieAttributeAssignor(){
public void assign(HttpCookie cookie, String attrName, String attrValue) { public void assign(HttpCookie cookie,
String attrName,
String attrValue) {
cookie.setSecure(true); cookie.setSecure(true);
} }
}); });
assignors.put("httponly", new CookieAttributeAssignor(){ assignors.put("httponly", new CookieAttributeAssignor(){
public void assign(HttpCookie cookie, String attrName, String attrValue) { public void assign(HttpCookie cookie,
String attrName,
String attrValue) {
cookie.setHttpOnly(true); cookie.setHttpOnly(true);
} }
}); });
assignors.put("version", new CookieAttributeAssignor(){ assignors.put("version", new CookieAttributeAssignor(){
public void assign(HttpCookie cookie, String attrName, String attrValue) { public void assign(HttpCookie cookie,
String attrName,
String attrValue) {
try { try {
int version = Integer.parseInt(attrValue); int version = Integer.parseInt(attrValue);
cookie.setVersion(version); cookie.setVersion(version);
...@@ -1046,7 +948,9 @@ public final class HttpCookie implements Cloneable { ...@@ -1046,7 +948,9 @@ public final class HttpCookie implements Cloneable {
} }
}); });
assignors.put("expires", new CookieAttributeAssignor(){ // Netscape only assignors.put("expires", new CookieAttributeAssignor(){ // Netscape only
public void assign(HttpCookie cookie, String attrName, String attrValue) { public void assign(HttpCookie cookie,
String attrName,
String attrValue) {
if (cookie.getMaxAge() == MAX_AGE_UNSPECIFIED) { if (cookie.getMaxAge() == MAX_AGE_UNSPECIFIED) {
cookie.setMaxAge(cookie.expiryDate2DeltaSeconds(attrValue)); cookie.setMaxAge(cookie.expiryDate2DeltaSeconds(attrValue));
} }
...@@ -1054,8 +958,8 @@ public final class HttpCookie implements Cloneable { ...@@ -1054,8 +958,8 @@ public final class HttpCookie implements Cloneable {
}); });
} }
private static void assignAttribute(HttpCookie cookie, private static void assignAttribute(HttpCookie cookie,
String attrName, String attrName,
String attrValue) String attrValue)
{ {
// strip off the surrounding "-sign if there's any // strip off the surrounding "-sign if there's any
attrValue = stripOffSurroundingQuote(attrValue); attrValue = stripOffSurroundingQuote(attrValue);
...@@ -1073,11 +977,7 @@ public final class HttpCookie implements Cloneable { ...@@ -1073,11 +977,7 @@ public final class HttpCookie implements Cloneable {
* as Netscape spec, but without leading "Cookie:" token. * as Netscape spec, but without leading "Cookie:" token.
*/ */
private String toNetscapeHeaderString() { private String toNetscapeHeaderString() {
StringBuilder sb = new StringBuilder(); return getName() + "=" + getValue();
sb.append(getName() + "=" + getValue());
return sb.toString();
} }
/* /*
...@@ -1101,15 +1001,16 @@ public final class HttpCookie implements Cloneable { ...@@ -1101,15 +1001,16 @@ public final class HttpCookie implements Cloneable {
static final TimeZone GMT = TimeZone.getTimeZone("GMT"); static final TimeZone GMT = TimeZone.getTimeZone("GMT");
/* /*
* @param dateString a date string in one of the formats * @param dateString
* defined in Netscape cookie spec * a date string in one of the formats defined in Netscape cookie spec
* *
* @return delta seconds between this cookie's creation * @return delta seconds between this cookie's creation time and the time
* time and the time specified by dateString * specified by dateString
*/ */
private long expiryDate2DeltaSeconds(String dateString) { private long expiryDate2DeltaSeconds(String dateString) {
for (int i = 0; i < COOKIE_DATE_FORMATS.length; i++) { for (int i = 0; i < COOKIE_DATE_FORMATS.length; i++) {
SimpleDateFormat df = new SimpleDateFormat(COOKIE_DATE_FORMATS[i], Locale.US); SimpleDateFormat df = new SimpleDateFormat(COOKIE_DATE_FORMATS[i],
Locale.US);
df.setTimeZone(GMT); df.setTimeZone(GMT);
try { try {
Date date = df.parse(dateString); Date date = df.parse(dateString);
...@@ -1121,8 +1022,6 @@ public final class HttpCookie implements Cloneable { ...@@ -1121,8 +1022,6 @@ public final class HttpCookie implements Cloneable {
return 0; return 0;
} }
/* /*
* try to guess the cookie version through set-cookie header string * try to guess the cookie version through set-cookie header string
*/ */
...@@ -1184,10 +1083,10 @@ public final class HttpCookie implements Cloneable { ...@@ -1184,10 +1083,10 @@ public final class HttpCookie implements Cloneable {
* 2) but not the comma surrounding by double-quotes, which is the comma * 2) but not the comma surrounding by double-quotes, which is the comma
* inside port list or embeded URIs. * inside port list or embeded URIs.
* *
* @param header the cookie header string to split * @param header
* * the cookie header string to split
* @return list of strings; never null
* *
* @return list of strings; never null
*/ */
private static List<String> splitMultiCookies(String header) { private static List<String> splitMultiCookies(String header) {
List<String> cookies = new java.util.ArrayList<String>(); List<String> cookies = new java.util.ArrayList<String>();
...@@ -1197,7 +1096,8 @@ public final class HttpCookie implements Cloneable { ...@@ -1197,7 +1096,8 @@ public final class HttpCookie implements Cloneable {
for (p = 0, q = 0; p < header.length(); p++) { for (p = 0, q = 0; p < header.length(); p++) {
char c = header.charAt(p); char c = header.charAt(p);
if (c == '"') quoteCount++; if (c == '"') quoteCount++;
if (c == ',' && (quoteCount % 2 == 0)) { // it is comma and not surrounding by double-quotes if (c == ',' && (quoteCount % 2 == 0)) {
// it is comma and not surrounding by double-quotes
cookies.add(header.substring(q, p)); cookies.add(header.substring(q, p));
q = p + 1; q = p + 1;
} }
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册